1423. Maximum Points You Can Obtain from Cards

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

这道题利用滑动窗口可解,设一长度为的滑动窗口,以步长为1在上滑动,剩余元素之和则为带求张卡牌之和,主要代码如下:

class Solution:
    def maxScore(self, cardPoints: List[int], k: int) -> int:
        n = len(cardPoints)
        total_sum = sum(cardPoints)
        window = sum(cardPoints[:n - k])
        result = total_sum - window
        for i in range(1, k+1):
            window -= cardPoints[i - 1]
            window += cardPoints[i + n - k - 1]
            result = max(result, total_sum - window)
        return result
            

你可能感兴趣的:(1423. Maximum Points You Can Obtain from Cards)