Maximum Average Subarray I
Find the contiguous subarray of length k that has the maximum average value using the sliding window technique.
Problem Statement
You are given an integer array nums consisting of n elements, and an integer k.
Find a contiguous subarray whose length is equal to k that has the maximum average value and return this value.
Interactive Visualization
fun findMaxAverage(nums: IntArray, k: Int): Double { var windowSum = nums.take(k).sum() var maxSum = windowSum for (i in k until nums.size) { windowSum += nums[i] - nums[i - k] maxSum = maxOf(maxSum, windowSum) } return maxSum.toDouble() / k}
Status
Execution Log
How It Works
Key Insight
The sliding window technique allows us to find the maximum sum subarray of size k in O(n) time. Instead of recalculating the sum for each window from scratch, we maintain a running sum and update it by adding the new element entering the window and subtracting the element leaving the window.
Algorithm Steps
- Initialize the first window: Calculate the sum of the first k elements. This is our initial window_sum and max_sum.
- Slide the window: For each position from k to n-1:
- Add the new element entering the window (nums[i])
- Subtract the element leaving the window (nums[i-k])
- Update max_sum if current window_sum is greater
- Return the result: Divide max_sum by k to get the maximum average.