Given a binary array nums and an integer k, return the maximum number of consecutive 1’s in the array if you can flip at most k 0’s.
?
Input: nums = [1,1,1,0,0,0,1,1,1,1,0], k = 2
Output: 6
Explanation: [1,1,1,0,0,1,1,1,1,1,1]
Bolded numbers were flipped from 0 to 1. The longest subarray is underlined.
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
Explanation: [0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1]
Bolded numbers were flipped from 0 to 1. The longest subarray is underlined.
From: LeetCode
Link: 1004. Max Consecutive Ones III
To solve the “Max Consecutive Ones III” problem in C, you’ll need to implement a function that uses the sliding window technique. The idea is to maintain a window that can include at most k zeros. As you traverse the array, you expand the window to the right by including ones and flipping zeros (up to k times). If you encounter more than k zeros, you shrink the window from the left until the number of zeros in the window is k again. The maximum size of this window at any point gives you the maximum number of consecutive ones after flipping at most k zeros.
int longestOnes(int* nums, int numsSize, int k) {
int left = 0, right = 0;
int maxLen = 0;
int zeroCount = 0;
for (right = 0; right < numsSize; right++) {
// If the current element is 0, increment the zero count
if (nums[right] == 0) {
zeroCount++;
}
// If the number of zeros exceeds k, move the left pointer forward
while (zeroCount > k) {
if (nums[left] == 0) {
zeroCount--;
}
left++;
}
// Update the maximum length
maxLen = (right - left + 1 > maxLen) ? right - left + 1 : maxLen;
}
return maxLen;
}