Loading
Leetcode / 643. Maximum Average Subarray I

Pick a programming language:

Here is the source code for the solution to this problem.

class Solution {
    public double findMaxAverage(int[] nums, int k) {
        int sum = 0;
        for (int i = 0; i < k; i++) {
            sum += nums[i];
        }

        int maxSum = sum;
        for (int i = k; i < nums.length; i++) {
            // slide the window
            sum -= nums[i - k];
            sum += nums[i];

            if (sum > maxSum) {
                maxSum = sum;
            }
        }

        return (double) maxSum / k;
    }
}
Did you like the lesson? 😆👍
Consider a donation to support our work: