💡 Current subarray sum is less than max_sum, so no update.
reconstruct
Calculate and return maximum average
Divide max_sum by k to get the maximum average subarray value: 51 / 4 = 12.75.
💡 Final step converts sum to average as required by the problem.
Line:return max_sum / k
💡 Maximum average subarray found efficiently using prefix sums and sliding window.
def findMaxAverage(nums, k):
n = len(nums) # STEP 1
prefix = [0] * (n + 1) # STEP 1
for i in range(n): # STEP 2-7
prefix[i + 1] = prefix[i] + nums[i] # STEP i+2
max_sum = float('-inf') # STEP 8
for i in range(k, n + 1): # STEP 9-11
current_sum = prefix[i] - prefix[i - k] # STEP i+8
if current_sum > max_sum: # STEP i+8
max_sum = current_sum # STEP i+8
return max_sum / k # STEP 12
if __name__ == '__main__':
nums = [1,12,-5,-6,50,3]
k = 4
print(findMaxAverage(nums, k)) # Expected output: 12.75
📊
Maximum Average Subarray I - Watch the Algorithm Execute, Step by Step
Watching each step helps you understand how prefix sums enable constant-time subarray sum calculation and how the sliding window moves to find the maximum average efficiently.
Step 1/12
·Active fill★Answer cell
expand
L=R
1
0
12
1
-5
2
-6
3
50
4
3
5
Metric: 0
expand
L=R
1
0
12
1
-5
2
-6
3
50
4
3
5
Metric: 1
expand
L ▼
1
0
R ▼
12
1
-5
2
-6
3
50
4
3
5
Metric: 13
expand
L ▼
1
0
12
1
R ▼
-5
2
-6
3
50
4
3
5
Metric: 8
expand
L ▼
1
0
12
1
-5
2
R ▼
-6
3
50
4
3
5
Metric: 2
expand
L ▼
1
0
12
1
-5
2
-6
3
R ▼
50
4
3
5
Metric: 52
expand
L ▼
1
0
12
1
-5
2
-6
3
50
4
R ▼
3
5
Metric: 55
record_answer
L=R
1
0
12
1
-5
2
-6
3
50
4
3
5
record_answer
L ▼
1
0
12
1
-5
2
R ▼
-6
3
50
4
3
5
Window: [1, 12, -5, -6]
Metric: 2
Answer: 2
record_answer
1
0
L ▼
12
1
-5
2
-6
3
R ▼
50
4
3
5
Window: [12, -5, -6, 50]
Metric: 51
Answer: 51
record_answer
1
0
12
1
L ▼
-5
2
-6
3
50
4
R ▼
3
5
Window: [-5, -6, 50, 3]
Metric: 42
Answer: 51
record_answer
1
0
L ▼
12
1
-5
2
-6
3
R ▼
50
4
3
5
Window: [12, -5, -6, 50]
Metric: 12.75
Answer: 12.75
Key Takeaways
✓ Prefix sums allow constant-time calculation of any fixed-length subarray sum.
Without prefix sums, summing each subarray would be O(k), making the algorithm slower.
✓ Sliding the window by one index and using prefix sums avoids redundant summations.
This shows how overlapping subarrays share computations, improving efficiency.
✓ Tracking max_sum and updating only when a larger sum is found ensures the correct maximum average.
This decision step is crucial to avoid missing the optimal subarray.
Practice
(1/5)
1. You are given an array of positive integers and a target sum. You need to find the length of the smallest contiguous subarray whose sum is at least the target. Which algorithmic approach guarantees an optimal O(n) time solution for this problem?
easy
A. Brute force nested loops checking all subarrays
B. Sorting the array and using binary search for subarray sums
C. Dynamic programming with memoization over subarray sums
D. Sliding window with two pointers adjusting window size dynamically
Solution
Step 1: Understand problem constraints
The problem requires finding the minimal length subarray with sum ≥ target, which suggests a variable-size window approach.
Step 2: Identify algorithm that adjusts window size efficiently
Sliding window with two pointers can expand and shrink the window in O(n) time, ensuring minimal length is found without checking all subarrays.
Final Answer:
Option D -> Option D
Quick Check:
Sliding window is known for O(n) minimal subarray sum solutions [OK]
Hint: Minimal subarray sum -> variable-size sliding window [OK]
Common Mistakes:
Thinking sorting helps with contiguous subarrays
Assuming DP is needed for minimal length
Using brute force for optimality
2. Consider the following code snippet implementing the optimal sliding window approach to check if s2 contains a permutation of s1. Given s1 = "ab" and s2 = "eidbaooo", what is the return value of the function?
easy
A. True
B. Raises an IndexError
C. False
D. Returns None
Solution
Step 1: Trace window expansion and counts
For s1 = "ab", count array has counts for 'a' and 'b'. Sliding window moves over s2 = "eidbaooo". When window covers substring "ba" starting at index 3, window_count matches count, so formed == required.
Step 2: Confirm return value
At this point, function returns True because a permutation of s1 is found in s2.
3. Consider the following Python code implementing the sliding window maximum using a monotonic deque. What is the returned result when calling maxSlidingWindow([2, 1, 3], 2)?
easy
A. [2, 3]
B. [2, 1, 3]
C. [3]
D. [1, 3]
Solution
Step 1: Trace the deque and result for each iteration
i=0: dq=[0], result=[]; i=1: nums[1]=1 < nums[0]=2, dq=[0,1], result=[]; i=2: nums[2]=3 > nums[1]=1 pop 1, nums[2]=3 > nums[0]=2 pop 0, dq=[2]; after i=1 (window [2,1]) result append nums[0]=2; after i=2 (window [1,3]) result append nums[2]=3.
Step 2: Collect final result
Result after full iteration is [2, 3].
Final Answer:
Option A -> Option A
Quick Check:
Output matches expected sliding window maximum for windows [2,1] and [1,3] [OK]
Hint: Deque stores indices of max candidates, popping smaller elements [OK]
Common Mistakes:
Appending result before window is full
Not removing indices outside the window
Confusing values and indices in deque
4. What is the time complexity of the optimal sliding window solution for the Grumpy Bookstore Owner problem when given an input array of length n and window size X?
medium
A. O(n)
B. O(n * X)
C. O(n + X)
D. O(n log n)
Solution
Step 1: Analyze outer loop
The code iterates over the array once to compute base satisfaction (O(n)).
Step 2: Analyze sliding window loop
The sliding window moves from start to end once, updating sums in O(1) per step, total O(n).
Final Answer:
Option A -> Option A
Quick Check:
Single pass with constant-time updates -> O(n) [OK]
Hint: Sliding window updates in O(1) per step [OK]
Common Mistakes:
Confusing with brute force O(n*X)
Adding X to n instead of linear
Assuming sorting needed
5. Suppose the bookstore owner can be calmed multiple times, each time for a continuous window of length X, possibly overlapping. How should the algorithm be modified to find the maximum total satisfied customers under this new condition?
hard
A. Sum all customers since calming multiple times removes grumpiness entirely
B. Run the original sliding window once and multiply the max extra by the number of windows allowed
C. Use a greedy approach to pick the top non-overlapping windows with highest extra satisfaction
D. Use dynamic programming to select multiple possibly overlapping windows maximizing total extra satisfaction
Solution
Step 1: Understand new problem constraints
Multiple calming windows allowed, possibly overlapping, so simple sliding window max sum is insufficient.
Step 2: Identify suitable approach
Dynamic programming can consider multiple windows and their overlaps to maximize total extra satisfaction.
Step 3: Why other options fail
Multiplying max extra ignores overlaps; greedy picking non-overlapping windows misses overlaps; summing all customers ignores grumpy states.
Final Answer:
Option D -> Option D
Quick Check:
DP handles multiple overlapping windows optimally [OK]
Hint: Multiple overlapping windows -> DP needed [OK]
Common Mistakes:
Assuming single window solution suffices
Ignoring overlaps in greedy
Over-simplifying to sum all customers
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.