0487. Max Consecutive Ones II
Description
**Input:** nums = [1,0,1,1,0]
**Output:** 4
**Explanation:** Flip the first zero will get the maximum number of consecutive 1s. After flipping, the maximum number of consecutive 1s is 4.**Input:** nums = [1,0,1,1,0,1]
**Output:** 4ac1: 2 pointers
class Solution {
public int findMaxConsecutiveOnes(int[] nums) {
// edge cases
if (nums == null || nums.length == 0) return 0;
int f = 0, s = 0, len = 0, zero = -1;
for (; f < nums.length; f++) {
if (nums[f] == 1) continue;
if (nums[f] == 0) {
if (zero == -1) { // first 0, flip
zero = f;
continue;
} else { // not 1st zero
len = Math.max(len, f - s);
s = zero + 1;
zero = f;
}
}
}
len = Math.max(len, f - s);
return len;
}
}ac2: sliding window
Last updated