1004. Max Consecutive Ones III
count zero
T: O(n)
S: O(1)
class Solution {
public int longestOnes(int[] nums, int k) {
int zeroCount = 0;
int left = 0;
int right = 0;
int result = 0;
while (right < nums.length) {
if (nums[right] == 0) {
zeroCount++;
}
right++;
if (zeroCount <= k) {
result = Math.max(result, right - left);
}
while (zeroCount > k) {
if (nums[left] == 0) {
zeroCount--;
}
left++;
}
}
return result;
}
}
/*
when match or lower k zero -> get ans,
when over k zero, start to shrink left
[1,1,1,0,0,0,1,1,1,1,0]
l
r
[1,1,1,0,1,1,1,1,1,1,1] zerocount < k 時 or zerocount == k 時. 都要計算
*/count one
Last updated
Was this helpful?