Max Consecutive Ones
Given a binary array nums, return the maximum number of consecutive 1s.
Intuition
Walk the array counting the current streak of 1s. A 0 breaks the streak, so reset the counter. Remember the longest streak seen.
Approach
Why re-counting from each index is wasteful
A first instinct is: for every position, count how long the run of 1s starting there is, and keep the longest — O(n²). But notice the runs overlap heavily; once you've measured a run, restarting the count one position later re-walks almost the same cells. We can measure every run in a single forward sweep instead.
Maintain the current streak as you walk
Keep one counter, streak, for the length of the run of 1s ending at the current position. A 1 extends the run (streak += 1); a 0 breaks it, so the run ends and we reset (streak = 0). That single number captures everything we need to know about the immediate past.
Record the best at every 1
Each time streak grows, compare it to best. Updating best on every 1 — not just at zeros or at the end — is what makes a run that reaches the very end of the array still count. Return best. O(n) time, O(1) space, one pass.
Solution & live demo
Edge cases
streak never resets, so best equals the array length.
streak stays 0 throughout; best returns 0.
best is updated on every 1, so a streak that ends only at the array's end is still captured.