1423. Maximum Points You Can Obtain from Cards

sliding window

T: O(n)
S: O(1)
class Solution {
    public int maxScore(int[] cardPoints, int k) {
        int n = cardPoints.length;
        int total = 0;
        for (int cardPoint : cardPoints) {
            total += cardPoint;
        }
        if (k == n) {
            return total;
        }
        
        int winSize = n - k;
        int res = 0;
        int winSum = 0;
        
        int left = 0;
        for (int right = 0; right < n; right++) {
            winSum += cardPoints[right];
            if (right - left + 1 > winSize) {
                winSum -= cardPoints[left];
                left++;
            }
            if (right - left + 1 == winSize) {
                res = Math.max(res, total - winSum);
            }
        }
        return res;
    }
}

/*
winsize = 1;
0. 1 2
[2,2,2]
2


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.

from start or end


n - k - 1 = 7 - 3 - 1 = 3

0      3 4     => 7 - 3 - 1 = 3
[1,2,3,4,5,6,1]
[__4___]
   [__4___]
     [__4___]  

cal total sum

max(total sum - sliding window sum)

T: O(n)
S: O(1)
*/

new version of sliding window

prefix sum idea

T: O(n)

S: O(1)

change to new template style

Last updated

Was this helpful?