Max Consecutive Ones - Problem
Find the Longest Streak of Consecutive 1's!

You're given a binary array nums containing only 0's and 1's. Your task is to find the maximum number of consecutive 1's in the array.

Goal: Return the length of the longest unbroken sequence of 1's.

Example: In the array [1,1,0,1,1,1], the longest consecutive sequence of 1's has length 3.

This is a classic problem that tests your ability to traverse an array while keeping track of streaks and maximums!

Input & Output

example_1.py โ€” Basic Case
$ Input: [1,1,0,1,1,1]
โ€บ Output: 3
๐Ÿ’ก Note: The longest sequence of consecutive 1's is [1,1,1] at the end, which has length 3.
example_2.py โ€” Single Element
$ Input: [1,0,1,1,0,1]
โ€บ Output: 2
๐Ÿ’ก Note: The longest sequence of consecutive 1's is [1,1] in the middle, which has length 2.
example_3.py โ€” All Zeros
$ Input: [0,0,0]
โ€บ Output: 0
๐Ÿ’ก Note: There are no 1's in the array, so the maximum consecutive 1's is 0.

Constraints

  • 1 โ‰ค nums.length โ‰ค 105
  • nums[i] is either 0 or 1
  • The array contains only binary values

Visualization

Tap to expand
๐Ÿƒโ€โ™‚๏ธ Running Streak TrackerArray: [1,1,0,1,1,1] โ†’ Find longest consecutive running days๐ŸƒDay 1Current: 1๐ŸƒDay 2Current: 2๐Ÿ˜ดDay 3Current: 0๐ŸƒDay 4Current: 1๐ŸƒDay 5Current: 2๐ŸƒDay 6Current: 3๐Ÿ† Longest Streak!Algorithm Steps1. Day 1 (1): Start streak! current=1, max=12. Day 2 (1): Continue streak! current=2, max=23. Day 3 (0): Rest day ๐Ÿ˜ด current=0, max=24. Day 4 (1): New streak starts! current=1, max=25. Day 5 (1): Continue new streak! current=2, max=26. Day 6 (1): New record! current=3, max=3 ๐Ÿ†Longest Running Streak: 3 Days
Understanding the Visualization
1
Track Current Streak
Keep count of consecutive running days (1's)
2
Reset on Rest Day
When you don't run (0), reset current streak to 0
3
Remember Best Streak
Always remember your longest streak so far
4
Continue Until End
Process the entire log to find the absolute maximum
Key Takeaway
๐ŸŽฏ Key Insight: We only need to track two numbers - our current streak and our best streak ever. When we hit a 0, we reset the current streak but keep our record!
Asked in
Google 25 Amazon 18 Meta 15 Microsoft 12
42.4K Views
Medium Frequency
~8 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen