Max Consecutive Ones III
Medium
Sliding WindowArray
Problem
You are given a binary array nums and an integer k.
Return the length of the longest run of consecutive 1s obtainable if you may flip at most k zeros to 1.
Example 1
Input: nums = [1,1,1,0,0,0,1,1,1,1,0], k = 2
Output: 6
Explain: Flip the two 0s at indices 4 and 5 to get six 1s in a row.
Example 2
Input: nums = [0,0,1,1,0,0,1,1,1,0,1,1,0,0,0,1,1,1,1], k = 3
Output: 10
Explain: Flipping three well-chosen 0s yields a window of ten 1s.
Constraints
- 1 ≤ nums.length ≤ 100000
- nums[i] is 0 or 1
- 0 ≤ k ≤ nums.length
Approach — Sliding Window
This is a Sliding Window problem. The idea: keep a moving window over the sequence, expanding and shrinking it while tracking the answer in a single pass. Work through the reference code below line by line, then re-derive it yourself in the editor — that's how the pattern sticks.
Complexity: O(n) time.
Solution code
Python
class Solution:
def longestOnes(self, nums, k):
left = zeros = best = 0
for right, x in enumerate(nums):
if x == 0:
zeros += 1
while zeros > k:
if nums[left] == 0:
zeros -= 1
left += 1
best = max(best, right - left + 1)
return best
Java
class Solution {
public int longestOnes(int[] nums, int k) {
int left = 0, zeros = 0, best = 0;
for (int right = 0; right < nums.length; right++) {
if (nums[right] == 0) zeros++;
// Shrink from the left until the window holds at most k zeros.
while (zeros > k) {
if (nums[left] == 0) zeros--;
left++;
}
best = Math.max(best, right - left + 1);
}
return best;
}
}
Practice it
Reading a solution isn't the same as being able to write it under pressure. Open this problem in the in-browser editor, hide the solution, and solve it from scratch — your code runs against real test cases instantly.
Solve Max Consecutive Ones III interactively → ← All solutions