LeetCode 1423: Maximum Points You Can Obtain from Cards

Problem Description

Explanation

To maximize the score, we need to find the subarray of length cardPoints.length - k with the minimum sum. The remaining k cards not included in this subarray will give us the maximum score. We can use a sliding window approach to find the subarray with the minimum sum efficiently.

  1. Initialize the sum of the first cardPoints.length - k elements as the initial minimum sum.
  2. Compute the total sum of all elements.
  3. Slide a window of size cardPoints.length - k over the array to find the minimum sum.
  4. Subtract the minimum sum from the total sum to get the maximum score.

The time complexity of this approach is O(n) where n is the length of the cardPoints array, and the space complexity is O(1).

Solutions

class Solution {
    public int maxScore(int[] cardPoints, int k) {
        int totalSum = 0;
        for (int num : cardPoints) {
            totalSum += num;
        }
        
        int windowSize = cardPoints.length - k;
        int windowSum = 0;
        for (int i = 0; i < windowSize; i++) {
            windowSum += cardPoints[i];
        }
        
        int minSum = windowSum;
        for (int i = windowSize; i < cardPoints.length; i++) {
            windowSum += cardPoints[i] - cardPoints[i - windowSize];
            minSum = Math.min(minSum, windowSum);
        }
        
        return totalSum - minSum;
    }
}

Loading editor...