Max Consecutive Ones

Length of the longest run of 1s in a binary array.

Easy
Time O(N) Space O(1)
LeetCode
2 min read
arrays counting

Problem#

Given a binary array nums, return the maximum number of consecutive 1s.

Examples#

  • [1,1,0,1,1,1]3.
  • [1,0,1,1,0,1]2.

Constraints#

  • 1 <= nums.length <= 10^5.

Hints#

Hint
One pass with a running counter, reset on zero.

Approach#

Track cur length of current run; reset to 0 on a zero, increment on a one. Update best after each update.

Solution#

Max Consecutive Ones
class Solution {
public:
int findMaxConsecutiveOnes(vector<int>& nums) {
int best = 0, cur = 0;
for (int v : nums) {
if (v == 1) { ++cur; best = max(best, cur); }
else cur = 0;
}
return best;
}
};

Editorial#

The simplest of run-length scans. Updating best only on increments is fine because zero-resets can’t improve best.

Complexity#

  • Time: O(N).
  • Space: O(1).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.