Description
There are several cards arranged in a row, and each card has an associated number of points. You want to maximize the sum of points by taking exactly k cards. You can only take cards from the beginning or end of the row. Return the maximum score you can obtain.
Examples
Input:
cardPoints = [1,2,3,4,5,6,1], k = 3Output:
12Explanation:
Take [1,6,5] = 12 points.
Input:
cardPoints = [2, 2, 2], k = 2Output:
4Explanation:
Since all cards have the same value, it doesn't matter which 2 cards taking from the ends. It is possible to take the first 2 cards [2, 2] or the last 2 cards [2, 2] or one from each end [2, 2], all giving us 4 points.
Input:
cardPoints = [9, 7, 7, 9, 7, 7, 9], k = 7Output:
55Explanation:
The task requires take all 7 cards since k equals the array length. The sum is 9 + 7 + 7 + 9 + 7 + 7 + 9 = 55 points. This is an edge case where it is necessary to take every card available.
Constraints
- •
1 ≤ cardPoints.length ≤ 10^5 - •
1 ≤ cardPoints[i] ≤ 10^4 - •
1 ≤ k ≤ cardPoints.length