Data Structures19 sections · 729 units
Open in Course

Max Average - Implementation

Sliding sum

Here's the solution:

function findMaxAverage(nums, k)
    // Build initial window
    windowSum := sum of nums[0] to nums[k-1]
    maxSum := windowSum

    // Slide the window
    for i from k to length of nums - 1
        windowSum := windowSum + nums[i] - nums[i - k]
        maxSum := max(maxSum, windowSum)

    return maxSum / k

Time: O(n)O(n). Space: O(1)O(1).