Pick exactly k cards from either end of the array to maximize the total points.
You are given an array of card points arranged in a row and an integer k.
You must take exactly k cards. Each time you can choose a card only from the leftmost or rightmost remaining card.
Return the maximum total points you can collect.
The key challenge is deciding how to split the k picks between the two ends so that the collected sum is as large as possible.
Input Format
- An integer array
cardPoints. - An integer
k.
Interpretation: cardPoints[i] is the score of the i-th card in the row.
Output Format
- Return a single integer: the maximum score obtainable by taking exactly
kcards from either end.
Constraints
1 <= cardPoints.length1 <= k <= cardPoints.lengthcardPoints[i]are integers- The optimal solution should be better than trying every possible pick sequence
Example 1
Input
cardPoints = [1,2,3,4,5,6,1], k = 3
Output
12
Explanation
Take 6, 5, and 1 from the right side for a total of 12.
Example 2
Input
cardPoints = [2,2,2], k = 2
Output
4
Explanation
Any two cards can be taken; the best total is 4.
Show 1 more example
Example 3
Input
cardPoints = [9,7,7,9,7,7,9], k = 7
Output
55
Explanation
You must take all cards, so the total is 55.
Premium problem context
Unlock deeper context for this problem
Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.