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?
currentis 2, the while body will be executed twice. If it is three, it will be executed three times. With anifit is guaranteed to be only executed at most once. Not sure I get what your question is – a loop loops until the condition becomes false.nums[left]isn't0, thewhileoperates differently. You say the second snippet 'passes', but it's not correct. Example input: 01111111000000000000000110. You always overwrite the answer, some sort ofans = Math.max()or similar needs to be involved somewhere.ans = Math.max()?