Leetcode 1423. Maximum Points You Can Obtain from Cards (python)

题目

在这里插入图片描述

解法1:O(n)

利用prefix sum,遍历k种不同组合

class Solution:
    def maxScore(self, cardPoints: List[int], k: int) -> int:
        prefix_sum = [0]
        tmp = 0
        for card in cardPoints:
            tmp += card
            prefix_sum.append(tmp)
        
        ans = 0
        for i in range(k+1):
            leftSum = prefix_sum[i]
            rightSum = prefix_sum[-1] - prefix_sum[len(cardPoints)-k+i]
            ans = max(ans,leftSum+rightSum)
            
        
        return ans

解法2:O(k)

其实上面的解法也可以O(K)完成,因为其实只需要算前k个和后k个的prefix sum就可以

这边提供一种新思路,假设先取前k个或者后k个,然后通过计算相应位置之前的差值更新答案

class Solution:
    def maxScore(self, cardPoints: List[int], k: int) -> int:
        n = len(cardPoints)
        
        start = k-1
        curr_sum = max_sum = sum(cardPoints[:k])
        
        for i in range(k):
            curr_sum -= cardPoints[start-i]
            curr_sum += cardPoints[n-1-i]
            max_sum = max(curr_sum,max_sum)
        
        return max_sum
已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页