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.
Example 1:
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.
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 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.
Constraints:
1 <= nums.length <= 105
nums[i]
is either 0
or 1
.0 <= k <= nums.length
class Solution {
public:
int longestOnes(vector& nums, int k) {
// Initialize two pointers i and j to represent the start and end of the window
int i = 0, j = 0;
// Iterate through the array using the end pointer (j)
while (j < nums.size()) {
// If the current element at the end pointer is 0, decrement the allowed flips (k)
if (nums[j] == 0) {
k--;
}
// If the allowed flips (k) become negative, adjust the window from the start pointer (i)
if (k < 0) {
// If the element at the start pointer is 0, increment the allowed flips (k)
if (nums[i] == 0) {
k++;
}
// Move the start pointer to the next element
i++;
}
// Move the end pointer to the next element
j++;
}
// The length of the longest subarray is given by the difference between end and start pointers
return j - i;
}
};
The primary objective of this function is to determine the length of the longest subarray in a binary array, represented by ‘nums’, that contains at most ‘k’ zeroes. This problem is solved by using a sliding window approach.
Let’s see the step-by-step approach to the problem:
After the loop completes, the function returns ‘( j -i )’ the length of the longest subarray containing at most ‘k’ zeroes.
Summary- This problem effectively finds the length of the longest subarray with at most ‘k’ zeroes, showcasing a practical implementation of the sliding window techniques.
Office:- 660, Sector 14A, Vasundhara, Ghaziabad, Uttar Pradesh - 201012, India