-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
Copy path_487.java
59 lines (56 loc) · 1.76 KB
/
_487.java
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
49
50
51
52
53
54
55
56
57
58
59
package com.fishercoder.solutions.firstthousand;
public class _487 {
public static class Solution1 {
/*
* I implemented this on my own after a quick read from https://leetcode.com/problems/max-consecutive-ones-ii/solution/
*/
public static int findMaxConsecutiveOnes(int[] nums) {
int left = 0;
int right = 0;
int zeroes = 0;
int ans = 0;
while (right < nums.length) {
if (nums[right] == 0) {
zeroes++;
}
if (zeroes <= 1) {
ans = Math.max(ans, right - left + 1);
} else {
while (left < nums.length && zeroes > 1) {
if (nums[left] == 0) {
zeroes--;
}
left++;
}
}
right++;
}
return ans;
}
}
public static class Solution2 {
/*
* This is a more generic solution adapted from https://leetcode.com/problems/max-consecutive-ones-iii/, just set k = 1 here.
*/
public static int findMaxConsecutiveOnes(int[] nums) {
int len = nums.length;
int left = 0;
int right = 0;
int ans = 0;
int k = 1;
for (; right < len; right++) {
if (nums[right] == 0) {
k--;
}
while (k < 0) {
if (nums[left] == 0) {
k++;
}
left++;
}
ans = Math.max(ans, right - left + 1);
}
return ans;
}
}
}