[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
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

思路

这道题有两种做法,一种是前缀和 + 滑动窗口,另一种是动态规划,我这里暂时先提供前一种做法。动态规划的思路我自己想清楚了日后再补充。这道题滑动窗口的思路也可以应用到 1509 题。

题设说的拿掉卡牌的规则是一定要从数组的两端拿,一共拿 k 张牌。那么我一开始可以先从数组的左边拿 k 张牌,设这 k 张牌的点数之和为 sum,然后每次从数组左边靠中间的部分去掉一张牌并用一张数组右侧的牌替换,看看所有卡牌点数的加和是否能更大。

复杂度

时间O(k)
空间O(1)

代码

Java实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution {
public int maxScore(int[] cardPoints, int k) {
int n = cardPoints.length;
int sum = 0;
for (int i = 0; i < k; i++) {
sum += cardPoints[i];
}

int index = 0;
int max = sum;
while (index < k) {
sum -= cardPoints[k - 1 - index];
sum += cardPoints[n - 1 - index];
max = Math.max(max, sum);
index++;
}
return max;
}
}

[LeetCode] 1423. Maximum Points You Can Obtain from Cards
https://shurui91.github.io/posts/4252400418.html
Author
Aaron Liu
Posted on
February 6, 2021
Licensed under