-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathMaxConsecutiveOnes2.java
More file actions
48 lines (39 loc) · 1.13 KB
/
MaxConsecutiveOnes2.java
File metadata and controls
48 lines (39 loc) · 1.13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
package array;
import java.util.LinkedList;
import java.util.Queue;
/**
* Description: https://leetcode.com/problems/max-consecutive-ones-ii
* Difficulty: Medium
* Time complexity: O(n)
* Space complexity: O(1)
*/
public class MaxConsecutiveOnes2 {
public int findMaxConsecutiveOnes(int[] nums) {
int flips = 1;
int left = 0;
int right = 0;
while (right < nums.length) {
if (nums[right] == 0) flips--;
if (flips < 0) {
if (nums[left] == 0) flips++;
left++;
}
right++;
}
return right - left;
}
public int findMaxConsecutiveOnesForDataStream(int[] nums) {
int flips = 1;
int left = 0;
int max = 0;
Queue<Integer> zeroPositions = new LinkedList<>();
for (int right = 0; right < nums.length; right++) {
if (nums[right] == 0) zeroPositions.offer(right);
if (zeroPositions.size() > flips) {
left = zeroPositions.poll() + 1;
}
max = Math.max(max, right - left + 1);
}
return max;
}
}