Leetcode|Simple|Interval Greedy|53. Maximum Subsequence Sum (violent or greedy)

Insert picture description here

1 Violence Law

Time complexity : O (n 2) O(n^2)O ( n2)

class Solution {
    
    
public:
    int maxSubArray(vector<int>& nums) {
    
    
        int maxSum = INT_MIN;
        for (int i = 0; i < nums.size(); i++) {
    
    
            int sum = 0;
            int curSum = INT_MIN;
            for (int j = i; j < nums.size(); j++) {
    
    
                sum += nums[j];
                curSum = max(curSum, sum);
            }
            maxSum = max(maxSum, curSum);
        }
        return maxSum;
    }
};

Insert picture description here

2 Interval Greedy Algorithm

Time complexity : O (n) O(n)O ( n )

局部最优:Stop adding up immediately when the current sum is negative, because the negative sum in the front will only pull down the sum in the back (case of all negative numbers)

全局最优: Select the largest "continuous sum"
Insert picture description here

class Solution {
    
    
public:
    int maxSubArray(vector<int>& nums) {
    
    
        int maxSum = INT_MIN;
        int curSum = 0;  // 当前区间中的和
        for (int i = 0; i < nums.size(); i++) {
    
    
            curSum += nums[i];
            maxSum = max(maxSum, curSum);
            // 核心:若之前的curSum为负数, 则置0, 因为前面的负数和一定会拉低后面的正和(全负数也满足)
            curSum = max(curSum, 0);  // 修正最大和的起始位置
        }
        return maxSum;
    }
};

Insert picture description here

Guess you like

Origin blog.csdn.net/SL_World/article/details/114965077