Skip to content

Instantly share code, notes, and snippets.

@Allan-Gong
Created October 24, 2021 04:05
Show Gist options
  • Save Allan-Gong/280b8ef88bc3178f5663ebf9f34418d3 to your computer and use it in GitHub Desktop.
Save Allan-Gong/280b8ef88bc3178f5663ebf9f34418d3 to your computer and use it in GitHub Desktop.
1004
class Solution {
public int longestOnes(int[] nums, int k) {
int n = nums.length;
int countOfZero = 0;
int longest = 0;
//. s
// [0,1,1,0,0,0,1,1,1,1,0]
// sliding window template
int s = 0;
for (int f = 0; f < n; f++) {
// check the element af num[f]
if (nums[f] == 0) {
countOfZero++;
}
// we got more 0s than allowed ?
while (countOfZero > k) {
// start move slow pointer until we have k zeros between nums[s..f]
if (nums[s] == 0) countOfZero--;
s++;
}
// we got a candidate
longest = Math.max(longest, f-s+1);
/*
// when reached threshold
while (countOfZero == k) { // 1,1,0,0,1,1,1,0,1,1
for (int i = s; i <= f; i++) System.out.print(nums[i] + ",");
// System.out.println("-----");
// between s and f, we have a potential candidate
longest = Math.max(longest, f-s+1);
// continue move the slow pointer until the threshold is broken
if (nums[s] == 0) countOfZero--;
s++;
}
// countOfZero < k
// System.out.println("longest: " + longest);
*/
}
return longest;
}
// s. f
// [0,0,1,1,0,0,1,1,1,0,1,1,0,0,0,1,1,1,1] // 1,1,0,0,1,1,1,0,1,1 0
//. 3
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment