Max Consecutive Ones
Easy
Topics
Given a binary array nums, return the maximum number of consecutive 1s.
Example 1
No window bookkeeping is needed because nothing is ever allowed inside the run.
Cells are the array values; the small numbers underneath are indices.
Input: nums = [1,1,0,1,1,1] Output: 3
Example 2
Input: nums = [1,0,1,1,0,1] Output: 2
Constraints
- 1 <= nums.length <= 10^5
- nums[i] is 0 or 1
Editorial — intuition, approach, complexity and pitfalls
Intuition
Track the length of the run ending at the current position. A 1 extends it; a 0 ends it. The answer is the largest value that running length ever takes.
That is the whole algorithm, and it needs two variables. The reason it is worth stating carefully is the reset: on a 0 the current run goes to 0, not to 1, and not left alone.
Approach
current = 0,best = 0.- For each element:
current = current + 1if it is 1, else 0; thenbest = max(best, current).
Dry Run
nums = [1,1,0,1,1,1]
1 current=1 best=1
1 current=2 best=2
0 current=0 best=2
1 current=1 best=2
1 current=2 best=2
1 current=3 best=3
answer 3Complexity
- Time — O(n): one pass.
- Space — O(1): two integers.
Common Pitfalls
- Updating
bestonly when a 0 is seen. An array ending in 1s then never records its final run —[1,1,1]returns 0. - Resetting
currentto 1 instead of 0 on a zero, which counts the zero as part of a run. - Returning
currentrather thanbest. - Assuming the array contains only 1s and 0s without it being stated. Here it is guaranteed; in the follow-up variant that allows flipping a zero, this scan becomes a sliding window.
Full Solution — all languages
class Solution:
def findMaxConsecutiveOnes(self, nums):
best = cur = 0
for x in nums:
cur = cur + 1 if x == 1 else 0
best = max(best, cur)
return bestimport java.util.*;
class Solution {
public int findMaxConsecutiveOnes(int[] nums) {
int best = 0, cur = 0;
for (int x : nums) {
cur = x == 1 ? cur + 1 : 0;
best = Math.max(best, cur);
}
return best;
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: int findMaxConsecutiveOnes(vector<int>& nums) {
int best = 0, cur = 0;
for (int x : nums) {
cur = x == 1 ? cur + 1 : 0;
best = max(best, cur);
}
return best;
}
};/**
* @param {number[]} nums
* @return {number}
*/ var findMaxConsecutiveOnes = function(nums) {
let best = 0, cur = 0;
for (const x of nums) {
cur = x === 1 ? cur + 1 : 0;
if (cur > best) best = cur;
}
return best;
};