Given a binary array containing only 0s and 1s, return the length of the longest run of consecutive 1s.
Video coming soon
We're producing a video walkthrough — check back soon.
Given a binary array containing only 0s and 1s, return the length of the longest run of consecutive 1s.
The gentlest possible taste of a sliding window: a window that only ever grows or resets, never shrinks from the middle. It's the natural stepping stone before this course's real fixed- and variable-size window problems.
Whenever a problem asks for the longest or shortest contiguous run satisfying a simple condition, track a running window length that resets the instant the condition breaks.
Scan the array while keeping two counters: the current run length and the best run seen so far. Seeing a 1 extends the current run by one; seeing a 0 resets the current run to zero. After every step, update the best-so-far if the current run is longer. One pass, constant extra space.
class Solution {
public int findMaxConsecutiveOnes(int[] nums) {
int best = 0, current = 0;
for (int num : nums) {
current = (num == 1) ? current + 1 : 0;
best = Math.max(best, current);
}
return best;
}
}