#1004
Max Consecutive Ones III
MediumArrayBinary SearchSliding WindowPrefix SumSliding WindowTwo Pointers
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
The optimal approach uses the sliding window technique to maintain a window of valid elements (1's and up to k flipped 0's). This allows us to efficiently find the maximum length of consecutive 1's without checking every subarray.
⚙️
Algorithm
4 steps- 1Step 1: Initialize two pointers (left and right) and a variable to count zeros in the current window.
- 2Step 2: Expand the right pointer to include more elements in the window.
- 3Step 3: If the count of zeros exceeds k, move the left pointer to reduce the window size until the count of zeros is k or less.
- 4Step 4: Update the maximum length of the window whenever the condition is satisfied.
solution.py15 lines
1# Full working Python code
2
3def longestOnes(nums, k):
4 left = 0
5 zero_count = 0
6 max_length = 0
7 for right in range(len(nums)):
8 if nums[right] == 0:
9 zero_count += 1
10 while zero_count > k:
11 if nums[left] == 0:
12 zero_count -= 1
13 left += 1
14 max_length = max(max_length, right - left + 1)
15 return max_lengthℹ
Complexity note: The time complexity is O(n) because we only traverse the array once with two pointers. The space complexity is O(1) since we are using a constant amount of extra space.
- 1Using a sliding window allows us to efficiently manage the count of zeros without needing nested loops.
- 2The maximum length is updated only when the current window is valid, which avoids unnecessary calculations.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.