Skip to content

Commit 89a4460

Browse files
add a solution for 487
1 parent e2e8f68 commit 89a4460

File tree

2 files changed

+35
-5
lines changed

2 files changed

+35
-5
lines changed

Diff for: src/main/java/com/fishercoder/solutions/_487.java

+26
Original file line numberDiff line numberDiff line change
@@ -30,4 +30,30 @@ public static int findMaxConsecutiveOnes(int[] nums) {
3030
return ans;
3131
}
3232
}
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+
}
3359
}

Diff for: src/test/java/com/fishercoder/_487Test.java

+9-5
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,22 @@
11
package com.fishercoder;
22

33
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;
66

7-
import static junit.framework.Assert.assertEquals;
7+
import static org.junit.jupiter.api.Assertions.assertEquals;
88

99
public class _487Test {
1010
private static _487.Solution1 soution1;
11+
private static _487.Solution2 soution2;
1112
private static int[] nums;
1213
private static int expected;
1314
private static int actual;
1415

15-
@BeforeClass
16-
public static void setup() {
16+
@BeforeEach
17+
public void setup() {
1718
soution1 = new _487.Solution1();
19+
soution2 = new _487.Solution2();
1820
}
1921

2022
@Test
@@ -23,6 +25,8 @@ public void test1() {
2325
expected = 6;
2426
actual = soution1.findMaxConsecutiveOnes(nums);
2527
assertEquals(expected, actual);
28+
actual = soution2.findMaxConsecutiveOnes(nums);
29+
assertEquals(expected, actual);
2630

2731
}
2832

0 commit comments

Comments
 (0)