[LeetCode] 1423. Maximum Points You Can Obtain from Cards
There are several cards arranged in a row, and each card has an associated number of points. The points are given in the integer array cardPoints.
In one step, you can take one card from the beginning or from the end of the row. You have to take exactly k cards.
Your score is the sum of the points of the cards you have taken.
Given the integer array cardPoints and the integer k, return the maximum score you can obtain.
Example 1:
Input: cardPoints = [1,2,3,4,5,6,1], k = 3
Output: 12
Explanation: After the first step, your score will always be 1. However, choosing the rightmost card first will maximize your total score. The optimal strategy is to take the three cards on the right, giving a final score of 1 + 6 + 5 = 12.
Example 2:
Input: cardPoints = [2,2,2], k = 2
Output: 4
Explanation: Regardless of which two cards you take, your score will always be 4.
Example 3:
Input: cardPoints = [9,7,7,9,7,7,9], k = 7
Output: 55
Explanation: You have to take all the cards. Your score is the sum of points of all cards.
Example 4:
Input: cardPoints = [1,1000,1], k = 1
Output: 1
Explanation: You cannot take the card in the middle. Your best score is 1.
Example 5:
Input: cardPoints = [1,79,80,1,1,1,200,1], k = 3
Output: 202
Constraints:
1 <= cardPoints.length <= 105
1 <= cardPoints[i] <= 104
1 <= k <= cardPoints.length
可获得的最大点数。
几张卡牌 排成一行,每张卡牌都有一个对应的点数。点数由整数数组 cardPoints 给出。 每次行动,你可以从行的开头或者末尾拿一张卡牌,最终你必须正好拿 k 张卡牌。 你的点数就是你拿到手中的所有卡牌的点数之和。 给你一个整数数组 cardPoints 和整数 k,请你返回可以获得的最大点数。来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/maximum-points-you-can-obtain-from-cards
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路
思路是固定长度的滑动窗口。题目要我们从总计 n 张卡牌里面拿出 k 张牌,确保拿到最大的点数。注意这 k 张牌必须要从数组的两侧拿,不能从中间拿。那么这里我们可以换一个思路,我们可以从数组中间拿 n - k 张牌,确保这 n - k 张牌的点数之和最小,然后用所有卡牌的点数总和 total 减去这 n - k 张牌的点数之和,得到的结果就是最大的点数。
复杂度
时间O(n)
空间O(1)
代码
Java实现
class Solution {
public int maxScore(int[] cardPoints, int k) {
int n = cardPoints.length;
int total = 0;
for (int num : cardPoints) {
total += num;
}
int sum = 0;
int kk = n - k;
for (int i = 0; i < kk; i++) {
sum += cardPoints[i];
}
int res = sum;
for (int i = kk; i < n; i++) {
sum += cardPoints[i];
sum -= cardPoints[i - kk];
res = Math.min(res, sum);
}
return total - res;
}
}