Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commitc74e9e7

Browse files
add a solution for 1423
1 parenta17a0c9 commitc74e9e7

File tree

2 files changed

+58
-1
lines changed

2 files changed

+58
-1
lines changed

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

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,4 +21,36 @@ public int maxScore(int[] cardPoints, int k) {
2121
returnmaxScore;
2222
}
2323
}
24+
25+
publicstaticclassSolution2 {
26+
/**
27+
* My own implementation after looking at hints on LeetCode.
28+
*/
29+
publicintmaxScore(int[]cardPoints,intk) {
30+
longsum =0;
31+
for (inti =0;i <cardPoints.length;i++) {
32+
sum +=cardPoints[i];
33+
}
34+
intwindowSize =cardPoints.length -k;
35+
if (windowSize ==0) {
36+
return (int)sum;
37+
}
38+
longwindowSum =0;
39+
intans =0;
40+
for (inti =0,j =i;i <cardPoints.length -windowSize &&j <=cardPoints.length +1; ) {
41+
if (j -i <windowSize) {
42+
windowSum +=cardPoints[j];
43+
j++;
44+
}elseif (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

Lines changed: 26 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,17 +8,42 @@
88

99
publicclass_1423Test {
1010
privatestatic_1423.Solution1solution1;
11+
privatestatic_1423.Solution2solution2;
1112
privatestaticint[]cardPoints;
13+
privatestaticintexpected;
14+
privatestaticintk;
1215

1316
@BeforeClass
1417
publicstaticvoidsetup() {
1518
solution1 =new_1423.Solution1();
19+
solution2 =new_1423.Solution2();
1620
}
1721

1822
@Test
1923
publicvoidtest1() {
2024
cardPoints =newint[]{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+
publicvoidtest2() {
33+
cardPoints =newint[]{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+
publicvoidtest3() {
42+
cardPoints =newint[]{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)

[8]ページ先頭

©2009-2025 Movatter.jp