classSolution { // 求 k 张点数的最大和,等价于求 n - k 张连续的牌的最小和 publicintmaxScore(int[] cardPoints, int k) { intn= cardPoints.length, m = n - k, sum = 0; for (inti=0; i < m; ++i) sum += cardPoints[i]; inttotal= sum, minSum = sum; for (inti= m; i < n; ++i) { total += cardPoints[i]; sum += cardPoints[i] - cardPoints[i - m]; minSum = Math.min(minSum, sum); } return total - minSum; } }
时间复杂度:$O(n)$
空间复杂度:$O(1)$
方法二:滑动窗口正向思维
1 2 3 4 5 6 7 8 9 10 11 12
classSolution { publicintmaxScore(int[] cardPoints, int k) { intn= cardPoints.length, sum = 0; for (inti=0; i < k; ++i) sum += cardPoints[i]; intans= sum; for (inti=1; i <= k; ++i) { sum += cardPoints[n - i] - cardPoints[k - i]; ans = Math.max(ans, sum); } return ans; } }