funcmaxScore(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 }
funcmin(a, b int)int { if a < b { return a } return b }
var maxScore = function(cardPoints, k) { const n = cardPoints.length; // 滑动窗口大小为 n-k const windowSize = n - k; // 选前 n-k 个作为初始值 let sum = 0; for (let i = 0; i < windowSize; ++i) { sum += cardPoints[i]; } let minSum = sum; for (let i = windowSize; i < n; ++i) { // 滑动窗口每向右移动一格,增加从右侧进入窗口的元素值,并减少从左侧离开窗口的元素值 sum += cardPoints[i] - cardPoints[i - windowSize]; minSum = Math.min(minSum, sum); } let totalSum = 0; for (let i = 0; i < n; i++) { totalSum += cardPoints[i]; } return totalSum - minSum; };
[sol1-C]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
intmaxScore(int* cardPoints, int cardPointsSize, int k) { int n = cardPointsSize; // 滑动窗口大小为 n-k int windowSize = n - k; // 选前 n-k 个作为初始值 int sum = 0; for (int i = 0; i < windowSize; i++) { sum += cardPoints[i]; } int ret = sum; int minSum = sum; for (int i = windowSize; i < n; ++i) { // 滑动窗口每向右移动一格,增加从右侧进入窗口的元素值,并减少从左侧离开窗口的元素值 sum += cardPoints[i] - cardPoints[i - windowSize]; minSum = fmin(minSum, sum); ret += cardPoints[i]; } return ret - minSum; }