[LeetCode] Max Consecutive Ones III

1004. Max Consecutive Ones III

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution {
public:
int longestOnes(vector<int>& nums, int k) {
int l = 0, r = 0, z = 0, n = nums.size(), res = 0;
while(r < n) {
if(nums[r++] == 0) z++;
while(z > k) {
if(nums[l++] == 0) z--;
}
res = max(res, r - l);
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/02/28/PS/LeetCode/max-consecutive-ones-iii/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.