File tree Expand file tree Collapse file tree 1 file changed +11
-7
lines changed
src/main/java/com/fishercoder/solutions Expand file tree Collapse file tree 1 file changed +11
-7
lines changed Original file line number Diff line number Diff line change 2
2
3
3
public class _1004 {
4
4
public static class Solution1 {
5
- public int longestOnes (int [] A , int k ) {
5
+ /**
6
+ * Two pointer technique, a.k.a sliding window.
7
+ */
8
+ public int longestOnes (int [] nums , int k ) {
6
9
int result = 0 ;
7
- int i = 0 ;
8
- for (int j = 0 ; j < A .length ; j ++) {
9
- if (A [ j ] == 0 ) {
10
+ int left = 0 ;
11
+ for (int right = 0 ; right < nums .length ; right ++) {
12
+ if (nums [ right ] == 0 ) {
10
13
k --;
11
14
}
12
15
while (k < 0 ) {
13
- if (A [i ] == 0 ) {
16
+ //in this case, we'll move the left pointer to the right
17
+ if (nums [left ] == 0 ) {
14
18
k ++;
15
19
}
16
- i ++;
20
+ left ++;
17
21
}
18
- result = Math .max (result , j - i + 1 );
22
+ result = Math .max (result , right - left + 1 );
19
23
}
20
24
return result ;
21
25
}
You can’t perform that action at this time.
0 commit comments