We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Maximum Points You Can Obtain from Cards

Difficulty: Medium


Problem Description

Given an integer array cardPoints representing points on cards arranged in a row, you can take exactly k cards from either the beginning or the end of the row. Your goal is to maximize the sum of the points of the cards you take.


Key Insights

  • You can choose cards from both ends of the array.
  • The maximum score can be obtained by taking a combination of cards from the left and right.
  • The problem can be approached using a sliding window technique to find the minimum sum of the cards you do not take.

Space and Time Complexity

Time Complexity: O(n)
Space Complexity: O(1)


Solution

To solve this problem, we can use a sliding window approach. Here’s the step-by-step breakdown:

  1. Calculate the total sum of the cardPoints.
  2. To maximize the points you can obtain by taking k cards, we can equivalently minimize the points of the cards we do not take. This means we need to find the minimum sum of n-k cards in the middle of the array.
  3. We can use a sliding window to find the sum of the first n-k cards, then slide the window to the right to include cards from the end, updating the minimum sum accordingly.
  4. Finally, subtract the minimum sum of the cards not taken from the total sum to get the maximum score.

Code Solutions

def maxPoints(cardPoints, k):
    n = len(cardPoints)
    total_sum = sum(cardPoints)
    
    # If k equals the length of cardPoints, take all points
    if k == n:
        return total_sum
    
    # Calculate the sum of the first n-k cards
    min_sum = current_sum = sum(cardPoints[:n - k])
    
    # Use a sliding window to find the minimum sum of n-k cards
    for i in range(n - k, n):
        current_sum = current_sum - cardPoints[i - (n - k)] + cardPoints[i]
        min_sum = min(min_sum, current_sum)
    
    # The maximum points is total points minus the minimum points from the middle
    return total_sum - min_sum
← Back to All Questions