This problem looks busy at first, but the accepted solution is built around one steady invariant. For 485. Max Consecutive Ones, the solution in this repository is mainly a straightforward implementation solution.
Guide
What?
We want to turn the problem statement into a smaller set of decisions the computer can repeat safely. 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: straightforward implementation.
Guide
When?
This pattern shows up when the brute force version has too many repeated checks, too many possible branches, or too much bookkeeping to do by hand. The accepted code reduces that pressure by storing exactly the information that remains useful later.
The important function names to track are findMaxConsecutiveOnes.
Guide
Why?
The win comes from making each line carry responsibility: store the useful state, discard the rest, keep moving.
- 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) to O(n log n), depending on the dominant loop or data structure operation
- Space: O(n) in the usual case for auxiliary containers or recursion
Guide
C++ Solution
Your submission
The accepted solution
01/**
02Given a binary array, find the maximum number of consecutive 1s in this array.
03
04Example 1:
05Input: [1,1,0,1,1,1]
06Output: 3
07Explanation: The first two digits or the last three digits are consecutive 1s.
08 The maximum number of consecutive 1s is 3.
09Note:
10
11The input array will only contain 0 and 1.
12The length of input array is a positive integer and will not exceed 10,000
13**/
14
15//Runtime: 40 ms, faster than 63.46% of C++ online submissions for Max Consecutive Ones.
16//Memory Usage: 11.9 MB, less than 55.07% of C++ online submissions for Max Consecutive Ones.
17class Solution {
18public:
19 int findMaxConsecutiveOnes(vector<int>& nums) {
20 int lastMax = 0, curMax = 0;
21 for(int num : nums){
22 if(num){
23 curMax++;
24 }else{
25 lastMax = max(lastMax, curMax);
26 curMax = 0;
27 }
28 }
29 return max(lastMax, curMax);
30 }
31};
Cost