Leetcode 1538 Solution

This article provides solution to leetcode question 1538 (maximum-points-you-can-obtain-from-cards)

https://leetcode.com/problems/maximum-points-you-can-obtain-from-cards

Solution

class Solution:
    def maxScore(self, cardPoints: List[int], k: int) -> int:
        win_size = len(cardPoints) - k

        if win_size == 0:
            return sum(cardPoints)

        win_sum = 0
        win_cnt = 0

        opt = sys.maxsize
        for i, card in enumerate(cardPoints):
            win_sum += card
            win_cnt += 1

            if win_cnt > win_size:
                win_sum -= cardPoints[i - win_size]
                win_cnt -= 1

            if win_cnt == win_size:
                opt = min(opt, win_sum)

        return sum(cardPoints) - opt