1423. 可获得的最大点数

1423. 可获得的最大点数

解法一: 正向计算

go
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
func maxScore(cardPoints []int, k int) int {
left := 0
sum := 0
for left < k {
sum += cardPoints[left]
left++
}
left--
right := len(cardPoints) - 1
ans := sum
for i := 0; i < k; i++ {
sum -= cardPoints[left]
sum += cardPoints[right]
left--
right--
ans = max(ans, sum)
}
return ans
}

func max(num1, num2 int) int {
if num1 >= num2 {
return num1
}
return num2
}

解法二: 反向计算

go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
func maxScore(cardPoints []int, k int) int {
allSum := 0
sum := 0
n := len(cardPoints)
m := n - k
for i := 0; i < m; i++ {
allSum += cardPoints[i]
sum += cardPoints[i]
}
curMin := sum
for i := m; i < n; i++ {
sum += cardPoints[i] - cardPoints[i - m]
curMin = min(curMin, sum)
allSum += cardPoints[i]
}
return allSum - curMin
}

func min(num1, num2 int) int {
if num1 <= num2 {
return num1
}
return num2
}
作者

wuhunyu

发布于

2023-12-03

更新于

2023-12-03

许可协议