-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMaxConsecutiveOnesIII.java
More file actions
43 lines (39 loc) · 1.26 KB
/
MaxConsecutiveOnesIII.java
File metadata and controls
43 lines (39 loc) · 1.26 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
package leetcode;
/**
* MaxConsecutiveOnesIII
* https://leetcode-cn.com/problems/max-consecutive-ones-iii
* 1004. 最大连续1的个数 III
* https://leetcode-cn.com/problems/max-consecutive-ones-iii/solution/hua-dong-chuang-kou-by-oshdyr-cwlc/
*
* @author tobin
* @since 2021-02-19
*/
public class MaxConsecutiveOnesIII {
public static void main(String[] args) {
MaxConsecutiveOnesIII sol = new MaxConsecutiveOnesIII();
System.out.println(sol.longestOnes(new int[]{0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1}, 3));
System.out.println(sol.longestOnes(new int[]{1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0}, 2));
}
public int longestOnes(int[] A, int K) {
int longest = 0;
int left = K;
int startIdx = 0;
for (int endIdx = 0; endIdx < A.length; endIdx++) {
if (A[endIdx] == 0) {
if (left > 0) {
left--;
} else {
if (A[startIdx] > 0) {
endIdx--;
}
startIdx++;
}
}
int curr = endIdx - startIdx + 1;
if (curr > longest) {
longest = curr;
}
}
return longest;
}
}