Algo-Sim › Sliding Window
Max Consecutive Ones III
Medium · Sliding Window · step through it in Java, Python and C++ on your own input
Given a binary array, return the longest run of 1s if you may flip at most k zeros.
Problem
You are given an array nums of 0s and 1s and an integer k. You may turn at most k of the 0s into 1s. Return the length of the longest contiguous run of 1s you can end up with.
Constraints
- 1 ≤ nums.length ≤ 10⁵
- nums[i] is 0 or 1
- 0 ≤ k ≤ nums.length
Edge cases to test
- k = 0: the longest run of 1s
- k ≥ the number of zeros: the whole array
- All zeros
Follow-up questions
- What if the input is a stream and k = 1?
- Remember only the position of the last zero and where the current window starts: O(1) memory (LC 487).
- Why can the window grow but never shrink by more than one?
- Only a longer window can beat the answer, so the window may slide without shrinking: it keeps its best length, each pointer still moves n times.
Solution
Java
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++;
}
while (zeros > k) {
if (nums[left] == 0) {
zeros--;
}
left++;
}
best = Math.max(best, right - left + 1);
}
return best;
}Python
def longest_ones(nums, k):
left = zeros = best = 0
for right in range(len(nums)):
if nums[right] == 0:
zeros += 1
while zeros > k:
if nums[left] == 0:
zeros -= 1
left += 1
best = max(best, right - left + 1)
return bestC++
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int longestOnes(vector<int> &nums, int k) {
int left = 0, zeros = 0, best = 0;
for (int right = 0; right < int(nums.size()); right++) {
if (nums[right] == 0) {
zeros++;
}
while (zeros > k) {
if (nums[left] == 0) {
zeros--;
}
left++;
}
best = std::max(best, right - left + 1);
}
return best;
}
};
More Sliding Window problems
- Best Time to Buy and Sell Stock (Easy)
- Minimum Size Subarray Sum (Medium)
- Maximum Sum Subarray of Size K (Easy)
- Fruit Into Baskets (Medium)
- Longest Substring Without Repeating Characters (Medium)
- Longest Repeating Character Replacement (Medium)
- Permutation in String (Medium)
- Find All Anagrams in a String (Medium)
- Minimum Window Substring (Hard)
- Subarrays with K Different Integers (Hard)