zoukankan      html  css  js  c++  java
  • 643. Maximum Average Subarray I

    package LeetCode_643
    
    /**
     * 643. Maximum Average Subarray I
     * https://leetcode.com/problems/maximum-average-subarray-i/
     * Given an array consisting of n integers, find the contiguous subarray of given length k that has the maximum average value.
     * And you need to output the maximum average value.
    Example 1:
    Input: [1,12,-5,-6,50,3], k = 4
    Output: 12.75
    Explanation: Maximum average is (12-5-6+50)/4 = 51/4 = 12.75
    
    Note:
    1. 1 <= k <= n <= 30,000.
    2. Elements of the given array will be in the range [-10,000, 10,000].
     * */
    class Solution {
        /*
        * solution: sliding window, Time:O(n), Space:O(1)
        * */
        fun findMaxAverage(nums: IntArray, k: Int): Double {
            var result = Int.MIN_VALUE
            var index = 0
            //keep tracking size k of window
            while (index + k - 1 < nums.size) {
                var windowSum = 0
                var j = index
                //window size is k
                var n = k
                //sum up k size of window
                while (n-- > 0) {
                    windowSum += nums[j++]
                }
                result = Math.max(result, windowSum)
                index++
            }
            return result * 1.0 / k
        }
    }
  • 相关阅读:
    10uF的电容能滤除什么频率的电源纹波?
    Integrate Logic Analyzer入门
    状态机
    Setup和Hold(Max/Min)分析
    RS232
    Vivado时序分析概念setup time, hold time
    python学习第34天
    python学习第33天
    python学习第32天
    python学习第31天
  • 原文地址:https://www.cnblogs.com/johnnyzhao/p/14244149.html
Copyright © 2011-2022 走看看