Max Consecutive Ones
Problem Statement:β
Given a binary arrayΒ nums, returnΒ the maximum number of consecutiveΒ 1's in the array.
Example 1:
Input: nums = [1,1,0,1,1,1]
Output: 3
Explanation: The first two digits or the last three digits are consecutive 1s. The maximum number of consecutive 1s is 3.
Example 2:
Input: nums = [1,0,1,1,0,1]
Output: 2
β Solution: Linear Scanβ
int findMaxConsecutiveOnes(vector<int>& binaryArray) {
int maxConsecutiveOnes = 0; // Stores the maximum count of consecutive 1s
int currentCount = 0; // Tracks the current streak of 1s
for (int i = 0; i < binaryArray.size(); i++) {
if (binaryArray[i] == 1) {
currentCount++; // Extend the streak when we find a 1
} else {
// Update the max if current streak ends
maxConsecutiveOnes = max(maxConsecutiveOnes, currentCount);
currentCount = 0; // Reset the streak
}
}
// Final check in case the array ends with a streak of 1s
maxConsecutiveOnes = max(maxConsecutiveOnes, currentCount);
return maxConsecutiveOnes;
}
π How It Worksβ
- You scan the array once, keeping a running count of consecutive 1s.
- Each time you see a
1, you incrementcurrentCount. - If you see a
0, you:- Compare
currentCountwithmaxConsecutiveOnesand update it if needed. - Reset
currentCountto 0.
- Compare
- After the loop ends, you again update
maxConsecutiveOnesto handle the case where the array ends with 1s.
π§© Key Logicβ
Thereβs no recurrence here β itβs a simple one-pass comparison-based logic:
maxConsecutiveOnes = max(maxConsecutiveOnes, currentCount)
β±οΈ Time & Space Complexityβ
| Metric | Value |
|---|---|
| β± Time | O(n) |
| π Space | O(1) |
- Single pass through the array.
- Only two integer variables used.
β οΈ Edge Casesβ
- All elements are
1β final max is updated at the end. - All elements are
0βmaxConsecutiveOnesremains 0. - Single element β works correctly for both
0and1.
π‘ Other Approachesβ
| Approach | Time | Space | Notes |
|---|---|---|---|
| Linear Scan (this) | O(n) | O(1) | β Most efficient |
| Segment Tree | O(log n) | O(n) | β Overkill |
| Sliding Window (Fixed Size) | Not applicable here | β | β Only works for fixed-length windows |
π Related Problemsβ
π¬