[Daily question] 918. Maximum sum of circular subarrays

[Daily question] 918. Maximum sum of circular subarrays

918. Maximum Sum of Circular Subarrays

topic description

Given a circular integer array nums of length n, return the largest possible sum of non-empty subarrays of nums.

A circular array means that the end of the array will be connected to the beginning in a ring. Formally, the next element of nums[i] is nums[(i + 1) % n] and the previous element of nums[i] is nums[(i - 1 + n) % n] .

The subarray may contain each element in the fixed buffer nums at most once. Formally, for subarrays nums[i], nums[i + 1], …, nums[j], there is no i <= k1, k2 <= j where k1 % n == k2 % n.

Example 1:

输入:nums = [1,-2,3,-2]
输出:3
解释:从子数组 [3] 得到最大和 3

Example 2:

输入:nums = [5,-3,5]
输出:10
解释:从子数组 [5,5] 得到最大和 5 + 5 = 10

Example 3:

输入:nums = [3,-2,2,-3]
输出:3
解释:从子数组 [3] 和 [3,-2,2] 都可以得到最大和 3

hint:

n == nums.length
1 <= n <= 3 * 104
-3 * 104 <= nums[i] <= 3 * 104​​​​​​​

problem solving ideas

Idea: If the ring is not considered, then it is the maximum sub-array sum, classic dynamic programming + sliding array problem. Considering the ring here, the discussion can be divided into two parts, the first part is the largest subarray sum, and the second part is the sum minus the smallest subarray sum.

class Solution {
public:
    int maxSubarraySumCircular(vector<int>& nums) {
        int n=nums.size();
        int max_s=INT_MIN;  //最大子序列和 不能为空
        int min_s=INT_MAX;  //最小子序列和 可以为空
        int num1=0,num2=0,sum=0;  //num1求最大子序列和 num2求最小子序列和 sum求总和
        for(int i=0;i<n;i++)
        {
            num1=max(num1,0)+nums[i];   //当前子序和
            max_s=max(max_s,num1);      //最大子序和
            num2=min(num2,0)+nums[i];  //当前子序和
            min_s=min(min_s,num2);      //最小子序和
            sum+=nums[i];               //总和
        }
        cout<<"max_s:"<<max_s<<endl;
        cout<<"min_s:"<<min_s<<endl;
        //如果最小等于总和 那么最大为空 比如-3 -2 -3
        return sum==min_s?max_s:max(max_s,sum-min_s);
    }
};

Summary: The largest subsequence sum cannot be empty, but the smallest subsequence sum can be empty.

class Solution {
public:
    int maxSubArray(vector<int>& nums) {
        int n=nums.size();
        int num=0;
        int res=INT_MIN;
        // 动态规划 + 滚动数组
        for(int i=0;i<n;i++)
        {
            num=max(num,0)+nums[i];
            res=max(res,num);
        }
        return res;
    }
};

Guess you like

Origin blog.csdn.net/qq_43779149/article/details/131839132