mediumSliding WindowPure DSA~20 min
Maximum Points Taking Cards from Both Ends
A row of point-valued cards lets you take exactly k cards, each from either the front or the back. Maximize the total points collected.
Problem
Given an integer array cardPoints and an integer k, take exactly k cards, each time from the beginning or the end of the row. Return the maximum total points obtainable.
Input
An integer array cardPoints and an integer k.
Output
An integer: the maximum points from taking k cards from the ends.
Constraints
- 1 <= cardPoints.length <= 100000
- 1 <= k <= cardPoints.length
- 1 <= cardPoints[i] <= 10^4
Examples
Example 1
Input
cardPoints = [1,2,3,4,5,6,1], k = 3
Output
12
Take the last three cards 5+6+1 = 12.
Example 2
Input
cardPoints = [2,2,2], k = 2
Output
4
Any two cards give 4.