comments | difficulty | edit_url | rating | source | tags | ||||
---|---|---|---|---|---|---|---|---|---|
true |
Medium |
1655 |
Weekly Contest 126 Q3 |
|
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 either0
or1
.0 <= k <= nums.length
We can iterate through the array, using a variable
After the iteration ends, the length of the window is the maximum number of consecutive 1s.
Note that in the process above, we do not need to loop to move the left boundary of the window to the right. Instead, we directly move the left boundary to the right by one position. This is because the problem asks for the maximum number of consecutive 1s, so the length of the window will only increase, not decrease. Therefore, we do not need to loop to move the left boundary to the right.
The time complexity is
Similar problems:
class Solution:
def longestOnes(self, nums: List[int], k: int) -> int:
l = cnt = 0
for x in nums:
cnt += x ^ 1
if cnt > k:
cnt -= nums[l] ^ 1
l += 1
return len(nums) - l
class Solution {
public int longestOnes(int[] nums, int k) {
int l = 0, cnt = 0;
for (int x : nums) {
cnt += x ^ 1;
if (cnt > k) {
cnt -= nums[l++] ^ 1;
}
}
return nums.length - l;
}
}
class Solution {
public:
int longestOnes(vector<int>& nums, int k) {
int l = 0, cnt = 0;
for (int x : nums) {
cnt += x ^ 1;
if (cnt > k) {
cnt -= nums[l++] ^ 1;
}
}
return nums.size() - l;
}
};
func longestOnes(nums []int, k int) int {
l, cnt := 0, 0
for _, x := range nums {
cnt += x ^ 1
if cnt > k {
cnt -= nums[l] ^ 1
l++
}
}
return len(nums) - l
}
function longestOnes(nums: number[], k: number): number {
let [l, cnt] = [0, 0];
for (const x of nums) {
cnt += x ^ 1;
if (cnt > k) {
cnt -= nums[l++] ^ 1;
}
}
return nums.length - l;
}