-
Notifications
You must be signed in to change notification settings - Fork 286
Expand file tree
/
Copy pathMaxConsecutiveOnesIII.java
More file actions
34 lines (32 loc) · 893 Bytes
/
MaxConsecutiveOnesIII.java
File metadata and controls
34 lines (32 loc) · 893 Bytes
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
class Solution {
// TC : O(n)
// SC : O(1)
public int longestOnes(int[] nums, int k) {
int start = 0;
int end = 0;
int maxLen = 0;
int flippedOnes = 0;
while(end<nums.length){
if(nums[end] ==1){
end++;
} else {
// nums[end] == 0
if(flippedOnes<k) {
flippedOnes++;
end++;
} else {
// reduce some flips
while(flippedOnes>=k) {
if(nums[start] == 0) {
flippedOnes--;
}
start++;
}
}
}
// System.out.println(end + " "+ start);
maxLen = Math.max(maxLen, end-start);
}
return maxLen;
}
}