- Notifications
You must be signed in to change notification settings - Fork 1.3k
/
Copy path_1423.java
57 lines (55 loc) · 1.9 KB
/
_1423.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
packagecom.fishercoder.solutions.secondthousand;
publicclass_1423 {
publicstaticclassSolution1 {
publicintmaxScore(int[] cardPoints, intk) {
intmaxScore = 0;
if (cardPoints.length <= k) {
for (intpoint : cardPoints) {
maxScore += point;
}
returnmaxScore;
}
for (inti = 0; i < k; i++) {
maxScore += cardPoints[i];
}
intrunningSum = maxScore;
for (inti = cardPoints.length - 1, j = 1; i >= 0 && j <= k; i--, j++) {
runningSum = runningSum - cardPoints[k - j] + cardPoints[i];
maxScore = Math.max(maxScore, runningSum);
}
returnmaxScore;
}
}
publicstaticclassSolution2 {
/*
* My own implementation after looking at hints on LeetCode.
*/
publicintmaxScore(int[] cardPoints, intk) {
longsum = 0;
for (inti = 0; i < cardPoints.length; i++) {
sum += cardPoints[i];
}
intwindowSize = cardPoints.length - k;
if (windowSize == 0) {
return (int) sum;
}
longwindowSum = 0;
intans = 0;
for (inti = 0, j = i;
i < cardPoints.length - windowSize && j <= cardPoints.length + 1; ) {
if (j - i < windowSize) {
windowSum += cardPoints[j];
j++;
} elseif (j - i == windowSize) {
ans = (int) Math.max(ans, sum - windowSum);
windowSum += cardPoints[j];
j++;
} else {
windowSum -= cardPoints[i];
i++;
}
}
return (int) Math.max(ans, sum - windowSum);
}
}
}