918. 环形子数组的最大和

题目链接 918. 环形子数组的最大和
思路 最大子数组和-简单变体
题解链接 没有思路?一张图秒懂!(Python/Java/C++/Go/JS)
关键点
时间复杂度 \(O(n)\)
空间复杂度 \(O(1)\)

代码实现:

class Solution:
    def maxSubarraySumCircular(self, nums: List[int]) -> int:
        max_answer = -inf
        min_answer = 0

        maxv = minv = 0
        for num in nums:
            maxv = max(maxv, 0) + num
            max_answer = max(max_answer, maxv)

            minv = min(minv, 0) + num
            min_answer = min(min_answer, minv)
        
        sum_ = sum(nums)
        if sum_ == min_answer:
            return max_answer
        return max(max_answer, sum_ - min_answer)
posted @ 2024-09-18 23:11  WrRan  阅读(3)  评论(0编辑  收藏  举报