Sliding Window· 15 min

Maximum Average Subarray I

LeetCode #643 · Easy · Interactive step-by-step visualization

Setup

Example inputnums = [1,12,-5,-6,50,3], k = 4
Step 1 / 11

Current step

1 / 11

Build the first fixed window. Exactly 4 contiguous items belong to each candidate. Window sum starts at 2.

Step log

nums, k = 4

CURRENT WINDOW
1
0
12
1
-5
2
-6
3
50
4
3
5
Current dotted windowSaved best range

current

2

best

2

Active cursor
Comparing
Best or completed
Leaving or removed
maximum-average-subarray-i.java
1public double findMaxAverage(int[] nums, int k) {
2 int sum = 0;
3 for (int i = 0; i < k; i++) sum += nums[i];
4 int best = sum;
5 for (int right = k; right < nums.length; right++) {
6 sum += nums[right] - nums[right - k];
7 best = Math.max(best, sum);
8 }
9 return (double) best / k;
10}
● Java
Time
O(n)
Space
O(1)
Pattern
sliding window
Frames
11