File tree 2 files changed +35
-5
lines changed
main/java/com/fishercoder/solutions
test/java/com/fishercoder
2 files changed +35
-5
lines changed Original file line number Diff line number Diff line change @@ -30,4 +30,30 @@ public static int findMaxConsecutiveOnes(int[] nums) {
30
30
return ans ;
31
31
}
32
32
}
33
+
34
+ public static class Solution2 {
35
+ /**
36
+ * This is a more generic solution adapted from https://leetcode.com/problems/max-consecutive-ones-iii/, just set k = 1 here.
37
+ */
38
+ public static int findMaxConsecutiveOnes (int [] nums ) {
39
+ int len = nums .length ;
40
+ int left = 0 ;
41
+ int right = 0 ;
42
+ int ans = 0 ;
43
+ int k = 1 ;
44
+ for (; right < len ; right ++) {
45
+ if (nums [right ] == 0 ) {
46
+ k --;
47
+ }
48
+ while (k < 0 ) {
49
+ if (nums [left ] == 0 ) {
50
+ k ++;
51
+ }
52
+ left ++;
53
+ }
54
+ ans = Math .max (ans , right - left + 1 );
55
+ }
56
+ return ans ;
57
+ }
58
+ }
33
59
}
Original file line number Diff line number Diff line change 1
1
package com .fishercoder ;
2
2
3
3
import com .fishercoder .solutions ._487 ;
4
- import org .junit .BeforeClass ;
5
- import org .junit .Test ;
4
+ import org .junit .jupiter . api . BeforeEach ;
5
+ import org .junit .jupiter . api . Test ;
6
6
7
- import static junit .framework . Assert .assertEquals ;
7
+ import static org . junit .jupiter . api . Assertions .assertEquals ;
8
8
9
9
public class _487Test {
10
10
private static _487 .Solution1 soution1 ;
11
+ private static _487 .Solution2 soution2 ;
11
12
private static int [] nums ;
12
13
private static int expected ;
13
14
private static int actual ;
14
15
15
- @ BeforeClass
16
- public static void setup () {
16
+ @ BeforeEach
17
+ public void setup () {
17
18
soution1 = new _487 .Solution1 ();
19
+ soution2 = new _487 .Solution2 ();
18
20
}
19
21
20
22
@ Test
@@ -23,6 +25,8 @@ public void test1() {
23
25
expected = 6 ;
24
26
actual = soution1 .findMaxConsecutiveOnes (nums );
25
27
assertEquals (expected , actual );
28
+ actual = soution2 .findMaxConsecutiveOnes (nums );
29
+ assertEquals (expected , actual );
26
30
27
31
}
28
32
You can’t perform that action at this time.
0 commit comments