uacs2024

导航

leetcode 918. 环形子数组的最大和

918. 环形子数组的最大和

做不出来,直接看题解

灵神题解

class Solution {
public:
    int maxSubarraySumCircular(vector<int>& nums) {
        int sum = accumulate(nums.begin(),nums.end(),0);
        int nowSum = 0,maxSubSum = INT_MIN,minSubSum = INT_MAX;
        for(int &num : nums){
            if(nowSum > 0)  nowSum += num;
            else  nowSum = num;
            maxSubSum = max(maxSubSum,nowSum);
        }
        nowSum = 0;
        for(int &num : nums){
            if(nowSum < 0)  nowSum += num;
            else  nowSum = num;
            minSubSum = min(minSubSum,nowSum);
        }

        if(minSubSum == sum)  return maxSubSum; //一定要注意判断值是否相等,不要写成if(minSubSum = sum)
        return max(maxSubSum,sum - minSubSum);
    }
};

 

posted on 2025-03-12 12:08  ᶜʸᵃⁿ  阅读(5)  评论(0)    收藏  举报