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 INPUT Binary Array nums[] 1 [0] 1 [1] 0 [2] 1 [3] 1 [4] 1 [5] Consecutive Groups: [1, 1] count = 2 [1, 1, 1] count = 3 Input: nums = [1,1,0,1,1,1] Array length: 6 Contains: 0s and 1s only ALGORITHM STEPS 1 Initialize Counters maxCount = 0, count = 0 2 Iterate Through Array for each element in nums 3 Check Element Value If 1: count++ If 0: reset count = 0 4 Update Maximum maxCount = max(maxCount, count) Tracking Variables idx val count maxCnt 0 1 1 1 1 1 2 2 2 0 0 2 3-5 1,1,1 1,2,3 2,2,3 FINAL RESULT Longest Consecutive Sequence 1 1 0 1 1 1 Max = 3 Output: 3 Verification: OK Indices [3,4,5] contain 3 consecutive 1s Time: O(n) | Space: O(1) Key Insight: Single pass with two variables: count tracks current consecutive 1s, maxCount stores the maximum. When encountering 0, reset count to 0. When encountering 1, increment count and update maxCount. This greedy approach ensures we find the longest sequence without needing extra space for storage. TutorialsPoint - Max Consecutive Ones | Single Pass - Optimal Solution
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