Working on a leetcode problem described as: "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."
I am using a sliding window approach and had produced the below code:
class Solution {
public int longestOnes(int[] nums, int k) {
int current = 0;
int left = 0;
int ans = 0;
for (int right = 0; right < nums.length; right++){
if (nums[right] == 0){
current++;
}
while (current > k){
if (nums[left] == 0){
current--;
}
left++;
}
ans = right - left + 1;
}
return ans;
}
}
This produces a logical error in the ouptut where the value returned is off by 1 in either direction depending on the test. I replaced the while
loop with in if
statement shown in the code below which fixed the error. Why is this the case?
class Solution {
public int longestOnes(int[] nums, int k) {
int current = 0;
int left = 0;
int ans = 0;
for (int right = 0; right < nums.length; right++){
if (nums[right] == 0){
current++;
}
if (current > k){
if (nums[left] == 0){
current--;
}
left++;
}
ans = right - left + 1;
}
return ans;
}
}
I expected the while
loop to run once and be equivalent as the block should evaluate the condition on each iteration and then act if the condition is true. What is happening here?