#1423

Maximum Points You Can Obtain from Cards

Medium
ArraySliding WindowPrefix SumSliding WindowPrefix Sum
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

Instead of checking all combinations, we can use the concept of removing a sub-array from the total points. By calculating the total points and subtracting the minimum points of the sub-array we don't take, we can efficiently find the maximum score.

⚙️

Algorithm

4 steps
  1. 1Step 1: Calculate the total points from all cards.
  2. 2Step 2: Identify the size of the sub-array to remove, which is n - k.
  3. 3Step 3: Use a sliding window to find the minimum sum of this sub-array.
  4. 4Step 4: Subtract this minimum sum from the total points to get the maximum score.
solution.py11 lines
1# Full working Python code
2
3def maxScore(cardPoints, k):
4    n = len(cardPoints)
5    total_pts = sum(cardPoints)
6    min_subarray_sum = sum(cardPoints[:n - k])
7    current_sum = min_subarray_sum
8    for i in range(n - k, n):
9        current_sum += cardPoints[i] - cardPoints[i - (n - k)]
10        min_subarray_sum = min(min_subarray_sum, current_sum)
11    return total_pts - min_subarray_sum

Complexity note: The time complexity is O(n) because we traverse the array a constant number of times, making it much more efficient than the brute-force approach.

  • 1The problem can be transformed into finding the minimum sum of a sub-array that we don't take.
  • 2Using a sliding window approach allows us to efficiently calculate the minimum sum.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.