Problem
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.
Examples
Example 1:
|
|
Example 2:
|
|
Example 3:
|
|
Solution
Method 1 - Brute Force
We can take x
cards from starting and k-x
card from the end. This means we iterate x
from 0 to k.
Time complexity wil be O(k*k-x) = O(k^2)
We can loop from left to right till k
and remaining sum from right to left till k-x
.
Method 2 - Sliding Window
We can use inversion here. Instead of finding max elements on the sides, we can find the smallest subarray sum of length len(cardPoints) - k
. Then the remaining k
element sum will be max.
Code
|
|
Method 3 - Using Prefix Sum
When taking a card from either left or right k
times, there will have 3 cases:
- All selected cards from the left.
- All selected cards from the right.
- Selected cards taken from both sides.
Why not create sum with first
k
elements on the left. Now, we can iterate from end to see if our current end sum is max or not.
Code
|
|
Complexity
- ⏰ Time complexity:
O(n)
, worst whenk = n
, all cards are counted. - 🧺 Space complexity:
O(1)