I've been doing some algorithm questions and just saw a solution for a problem that is like this:
public int longestOnes(int[] nums, int k) {
int windowStart = 0, windowEnd;
for (windowEnd = 0; windowEnd < nums.length; ++windowEnd) {
if (nums[windowEnd] == 0) k--;
if (k < 0 && nums[windowStart++] == 0) k++;
}
return windowEnd - windowStart;
}
Specifically in the part where windowStart is incremented (nums[windowStart++]), I understand that it will first fetch the value from nums array using the current windowStart value and then it will be incremented.
However, I don't understand exactly when this piece of code will be executed. Only when k < 0?
If so, is it correct to write this code like below:
public int longestOnes(int[] nums, int k) {
int windowStart = 0, windowEnd;
for (windowEnd = 0; windowEnd < nums.length; ++windowEnd) {
if (nums[windowEnd] == 0) k--;
if (k < 0 && nums[windowStart] == 0) k++;
if (k < 0) windowStart++;
}
return windowEnd - windowStart;
}
EDIT: I understand that in the third "if" k has been incremented and the condition is not gonna be the same. I'm just trying to wrap my head around it by writing that second "if" in a different way.
Somehow it seems to give me different results.
Would anyone know the difference and what exactly happens during that second condition (if (k < 0 && nums[windowStart] == 0) k++;)?