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
// @Title: 可获得的最大点数 (Maximum Points You Can Obtain from Cards)
// @Author: 15816537946@163.com
// @Date: 2021-02-07 20:22:11
// @Runtime: 68 ms
// @Memory: 8 MB


func maxScore(cardPoints []int, k int) int {
    n := len(cardPoints)
    // 滑动窗口大小为 n-k
    windowSize := n - k
    // 选前 n-k 个作为初始值
    sum := 0
    for _, pt := range cardPoints[:windowSize] {
        sum += pt
    }
    minSum := sum
    for i := windowSize; i < n; i++ {
        // 滑动窗口每向右移动一格,增加从右侧进入窗口的元素值,并减少从左侧离开窗口的元素值
        sum += cardPoints[i] - cardPoints[i-windowSize]
        minSum = min(minSum, sum)
    }
    total := 0
    for _, pt := range cardPoints {
        total += pt
    }
    return total - minSum
}

func min(a, b int) int {
    if a < b {
        return a
    }
    return b
}