487 Max Consecutive Ones II

1. Question

Example 1:
1
Input: [1,0,1,1,0]
2
3
Output: 4
4
5
Explanation:
6
Flip the first zero will get the the maximum number of consecutive 1s. After flipping, the maximum number of consecutive 1s is 4.
Copied!
Note:
  • The input array will only contain0and1.
  • The length of input array is a positive integer and will not exceed 10,000
Follow up: What if the input numbers come in one by one as an infinite stream? In other words, you can't store all numbers coming from the stream as it's too large to hold in memory. Could you solve it efficiently?

2. Implementation

(1) Two Pointers
1
class Solution {
2
public int findMaxConsecutiveOnes(int[] nums) {
3
if (nums == null || nums.length == 0) {
4
return 0;
5
}
6
7
int k = 1;
8
int zeroes = 0;
9
int maxLen = 0, start = 0, end = 0;
10
11
while (end < nums.length) {
12
if (nums[end] == 0) {
13
++zeroes;
14
}
15
++end;
16
17
while (zeroes > k) {
18
if (nums[start] == 0) {
19
--zeroes;
20
}
21
++start;
22
}
23
maxLen = Math.max(maxLen, end - start);
24
}
25
return maxLen;
26
}
27
}
Copied!
Follow Up
1
class Solution {
2
public int findMaxConsecutiveOnes(int[] nums) {
3
if (nums == null || nums.length == 0) {
4
return 0;
5
}
6
7
int k = 1;
8
int maxLen = 0;
9
Queue<Integer> zeroIndex = new LinkedList<>();
10
11
for (int start = 0, end = 0; end < nums.length; end++) {
12
if (nums[end] == 0) {
13
zeroIndex.add(end);
14
}
15
16
if (zeroIndex.size() > k) {
17
start = zeroIndex.remove() + 1;
18
}
19
maxLen = Math.max(maxLen, end - start + 1);
20
}
21
return maxLen;
22
}
23
}
Copied!

3. Time & Space Complexity

Two Pointers: 时间复杂度O(n), 空间复杂度O(1)
Follow up: 时间复杂度O(n), 空间复杂度O(k)