Maximum Points You Can Obtain from Cards Problem
Description
LeetCode Problem 1423.
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.
Constraints:
1 <= cardPoints.length <= 10^51 <= cardPoints[i] <= 10^41 <= k <= cardPoints.length
Solution
Approach: Sliding Window Over the Two Ends
Whatever order we pick the cards in, we end up with some i cards from the left end and k − i cards from the right end, for some i between 0 and k. So we only need the best of these k + 1 totals.
Start with i = 0: all k cards from the right, and compute their sum. Going from i to i + 1 changes just two cards: we gain cardPoints[i] from the left and give back cardPoints[n − k + i], the leftmost of the cards we had from the right. So each next total costs O(1), and we keep the maximum.
Equivalently, the cards we do not take form a contiguous block of n − k cards in the middle, and we are minimizing its sum. When k = n we take everything, and the loop handles that without a special case.
Complexity: O(k) time and O(1) extra space.
class Solution:
def maxScore(self, cardPoints: List[int], k: int) -> int:
n = len(cardPoints)
total = sum(cardPoints[n - k:]) # take all k cards from the right
ans = total
for i in range(k):
# take one more card from the left and give back the leftmost card taken from the right
total += cardPoints[i] - cardPoints[n - k + i]
ans = max(ans, total)
return ans