Max Consecutive Ones
Problem
Given a binary array nums, return the maximum number of consecutive 1s in the array.
nums = [1, 1, 0, 1, 1, 1]3def find_max_consecutive_ones(nums):
best = run = 0
for x in nums:
run = run + 1 if x == 1 else 0
if run > best: best = run
return best
function findMaxConsecutiveOnes(nums) {
let best = 0, run = 0;
for (const x of nums) {
run = x === 1 ? run + 1 : 0;
if (run > best) best = run;
}
return best;
}
class Solution {
public int findMaxConsecutiveOnes(int[] nums) {
int best = 0, run = 0;
for (int x : nums) {
run = x == 1 ? run + 1 : 0;
if (run > best) best = run;
}
return best;
}
}
int findMaxConsecutiveOnes(vector<int>& nums) {
int best = 0, run = 0;
for (int x : nums) {
run = x == 1 ? run + 1 : 0;
if (run > best) best = run;
}
return best;
}
Explanation
We want the longest unbroken stretch of 1s. The simple trick is to sweep through once with a running counter that grows on every 1 and snaps back to zero on every 0.
We keep run (length of the current streak of 1s) and best (longest streak seen). When the value is 1, do run = run + 1; otherwise reset run = 0.
After each step we update best if the current run is larger. Because the reset happens exactly where a 0 breaks the streak, run always reflects the length ending at the current position.
This single pass is enough — we never need to revisit earlier elements.
Example: [1, 1, 0, 1, 1, 1]. run reaches 2 over the first pair, resets at the 0, then climbs to 3 over the final three 1s, so best = 3.