This is one of those problems where the clean idea matters more than the amount of code. For 643. Maximum Average Subarray I, the solution in this repository is mainly a sliding window solution.
Guide
What?
The code is easier to read if we treat it as a controlled search through possible states. Instead of trying to be clever immediately, read the code as a sequence of questions:
- What state are we keeping?
- How do we move from one state to the next?
- When do we know the answer is already determined?
For this file, the main tools are: sliding window.
Guide
When?
Reach for this shape when a direct simulation would work logically but waste time revisiting the same information. The accepted code reduces that pressure by storing exactly the information that remains useful later.
The important function names to track are findMaxAverage.
Guide
Why?
The solution works because it narrows the problem until every update has a clear reason to exist.
- The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.
Guide
How?
Walk through the solution in this order:
- Start from the smallest reliable state.
- Expand one legal move at a time.
- Cache, count, or merge information as soon as it becomes settled.
- Let the final stored value answer the original question.
The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.
Guide
Complexity
- Time: O(n)
- Space: O(1)
Guide
C++ Solution
Your submission
The accepted solution
01/**
02sliding window
03**/
04
05//Runtime: 176 ms, faster than 79.63% of C++ online submissions for Maximum Average Subarray I.
06//Memory Usage: 16.8 MB, less than 100.00% of C++ online submissions for Maximum Average Subarray I.
07
08/**
09time: O(n)
10space: O(1)
11**/
12
13class Solution {
14public:
15 double findMaxAverage(vector<int>& nums, int k) {
16 double maxsum;
17 double cursum = 0;
18
19 for(int i = 0; i < k; i++) cursum += nums[i];
20
21 maxsum = cursum;
22
23 for(int i = 1; i <= nums.size() - k; i++){
24 cursum = cursum - nums[i-1] + nums[i+k-1];
25 maxsum = max(maxsum, cursum);
26 }
27
28 return maxsum/k;
29 }
30};
Cost