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
    }
}

 

posted @ 2021-01-06 23:45  johnny_zhao  阅读(40)  评论(0编辑  收藏  举报