Max Consecutive Ones - Problem

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

The array contains only 0s and 1s.

Input & Output

Example 1 — Basic Case
$ Input: nums = [1,1,0,1,1,1]
Output: 3
💡 Note: The first two 1s have length 2, the last three 1s have length 3. Maximum is 3.
Example 2 — All Zeros
$ Input: nums = [0,0,0,0]
Output: 0
💡 Note: No consecutive 1s exist, so the maximum is 0.
Example 3 — All Ones
$ Input: nums = [1,1,1,1]
Output: 4
💡 Note: The entire array is consecutive 1s, so the maximum is 4.

Constraints

  • 1 ≤ nums.length ≤ 105
  • nums[i] is either 0 or 1

Visualization

Tap to expand
Max Consecutive Ones: Find longest streak of 1sInput: [1,1,0,1,1,1]110111Length: 2Length: 3Two consecutive sequences found: [1,1] and [1,1,1]Maximum length = max(2, 3) = 3Output: 3
Understanding the Visualization
1
Input Array
Binary array with 0s and 1s
2
Find Consecutive 1s
Identify all consecutive sequences of 1s
3
Return Maximum
Length of longest consecutive sequence
Key Takeaway
🎯 Key Insight: Track current consecutive count and reset on zeros to find maximum streak in one pass
Asked in
Google 15 Amazon 12 Microsoft 10 Facebook 8
56.7K Views
Medium Frequency
~15 min Avg. Time
2.1K 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