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: cardPoints = [1,2,3,4,5,6,1], k = 3 Output: 12
Example 2: cardPoints = [2,2,2], k = 2 Output: 4
Example 3: cardPoints = [9,7,7,9,7,7,9], k = 7 Output: 55
def max_score(cardPoints, k):
n = len(cardPoints)
total_sum = sum(cardPoints)
window_size = n - k
current_sum = sum(cardPoints[:window_size])
min_sum = current_sum
for i in range(window_size, n):
current_sum += cardPoints[i] - cardPoints[i - window_size]
min_sum = min(min_sum, current_sum)
return total_sum - min_sum
# Example Usage
cardPoints1 = [1, 2, 3, 4, 5, 6, 1]
k1 = 3
print(f"Maximum score for cardPoints {cardPoints1} and k={k1}: {max_score(cardPoints1, k1)}")
cardPoints2 = [2, 2, 2]
k2 = 2
print(f"Maximum score for cardPoints {cardPoints2} and k={k2}: {max_score(cardPoints2, k2)}")
cardPoints3 = [9, 7, 7, 9, 7, 7, 9]
k3 = 7
print(f"Maximum score for cardPoints {cardPoints3} and k={k3}: {max_score(cardPoints3, k3)}")
Problem Understanding:
cardPoints
representing points associated with cards arranged in a row.k
cards from either the beginning or the end of the row.Naive Approach (Brute Force):
k
cards from the beginning and end.def max_score_brute_force(cardPoints, k):
n = len(cardPoints)
max_score = 0
for i in range(k + 1):
current_score = sum(cardPoints[:i]) + sum(cardPoints[n - (k - i):])
max_score = max(max_score, current_score)
return max_score
Optimal Approach (Sliding Window):
n-k
with the minimum sum.n-k
with the minimum sum using a sliding window.Code Implementation (Optimal):
def max_score(cardPoints, k):
n = len(cardPoints)
total_sum = sum(cardPoints)
window_size = n - k
current_sum = sum(cardPoints[:window_size])
min_sum = current_sum
for i in range(window_size, n):
current_sum += cardPoints[i] - cardPoints[i - window_size]
min_sum = min(min_sum, current_sum)
return total_sum - min_sum
cardPoints
array once using a sliding window of size n-k
, where n
is the length of cardPoints
and k
is the number of cards to take.total_sum
, window_size
, current_sum
, and min_sum
.Handling them in code:
def max_score(cardPoints, k):
n = len(cardPoints)
if k == 0:
return 0
if k == n:
return sum(cardPoints)
total_sum = sum(cardPoints)
window_size = n - k
current_sum = sum(cardPoints[:window_size])
min_sum = current_sum
for i in range(window_size, n):
current_sum += cardPoints[i] - cardPoints[i - window_size]
min_sum = min(min_sum, current_sum)
return total_sum - min_sum