滑动窗口&动态规划-1031. 两个非重叠子数组的最大和

问题描述

image

问题求解

本题还挺巧妙,有点类似两数和的扩展题。
对于两个线段,我们可以固定右线段,然后寻找左线段的最大值。
固定右线段使用到的算法是滑动窗口,寻找左线段最大值的算法是动态规划。
时间复杂度:O(n)

class Solution:
    def maximizeWin(self, prizePositions: List[int], k: int) -> int:
        n = len(prizePositions)
        
        mx = [0] * n
        res = left = 0
        for right, pos in enumerate(prizePositions):
            while pos - prizePositions[left] > k:
                left += 1
            
            res = max(res, right - left + 1 + (mx[left - 1] if left else 0))
            mx[right] = max(mx[right - 1] if right else 0, right - left + 1)
        
        return res
posted @ 2024-09-11 18:17  hyserendipity  阅读(2)  评论(0编辑  收藏  举报