Skip to content

Commit c74e9e7

Browse files
add a solution for 1423
1 parent a17a0c9 commit c74e9e7

File tree

2 files changed

+58
-1
lines changed

2 files changed

+58
-1
lines changed

src/main/java/com/fishercoder/solutions/_1423.java

+32
Original file line numberDiff line numberDiff line change
@@ -21,4 +21,36 @@ public int maxScore(int[] cardPoints, int k) {
2121
return maxScore;
2222
}
2323
}
24+
25+
public static class Solution2 {
26+
/**
27+
* My own implementation after looking at hints on LeetCode.
28+
*/
29+
public int maxScore(int[] cardPoints, int k) {
30+
long sum = 0;
31+
for (int i = 0; i < cardPoints.length; i++) {
32+
sum += cardPoints[i];
33+
}
34+
int windowSize = cardPoints.length - k;
35+
if (windowSize == 0) {
36+
return (int) sum;
37+
}
38+
long windowSum = 0;
39+
int ans = 0;
40+
for (int i = 0, j = i; i < cardPoints.length - windowSize && j <= cardPoints.length + 1; ) {
41+
if (j - i < windowSize) {
42+
windowSum += cardPoints[j];
43+
j++;
44+
} else if (j - i == windowSize) {
45+
ans = (int) Math.max(ans, sum - windowSum);
46+
windowSum += cardPoints[j];
47+
j++;
48+
} else {
49+
windowSum -= cardPoints[i];
50+
i++;
51+
}
52+
}
53+
return (int) Math.max(ans, sum - windowSum);
54+
}
55+
}
2456
}

src/test/java/com/fishercoder/_1423Test.java

+26-1
Original file line numberDiff line numberDiff line change
@@ -8,17 +8,42 @@
88

99
public class _1423Test {
1010
private static _1423.Solution1 solution1;
11+
private static _1423.Solution2 solution2;
1112
private static int[] cardPoints;
13+
private static int expected;
14+
private static int k;
1215

1316
@BeforeClass
1417
public static void setup() {
1518
solution1 = new _1423.Solution1();
19+
solution2 = new _1423.Solution2();
1620
}
1721

1822
@Test
1923
public void test1() {
2024
cardPoints = new int[]{1, 2, 3, 4, 5, 6, 1};
21-
assertEquals(12, solution1.maxScore(cardPoints, 3));
25+
expected = 12;
26+
k = 3;
27+
assertEquals(expected, solution1.maxScore(cardPoints, k));
28+
assertEquals(expected, solution2.maxScore(cardPoints, k));
29+
}
30+
31+
@Test
32+
public void test2() {
33+
cardPoints = new int[]{96, 90, 41, 82, 39, 74, 64, 50, 30};
34+
expected = 536;
35+
k = 8;
36+
assertEquals(expected, solution1.maxScore(cardPoints, k));
37+
assertEquals(expected, solution2.maxScore(cardPoints, k));
38+
}
39+
40+
@Test
41+
public void test3() {
42+
cardPoints = new int[]{100, 40, 17, 9, 73, 75};
43+
expected = 248;
44+
k = 3;
45+
assertEquals(expected, solution1.maxScore(cardPoints, k));
46+
assertEquals(expected, solution2.maxScore(cardPoints, k));
2247
}
2348

2449
}

0 commit comments

Comments
 (0)