LeetCode OJ-- Maximum Subarray @

https://oj.leetcode.com/problems/maximum-subarray/

给了一个数组一列数,求其中的连续子数组的最大和。

O(n)复杂度

class Solution {
public:
    int maxSubArray(int A[], int n) {
        if(n == 0)
            return 0;
        
        int ans = INT_MIN;
        int tempSum = INT_MIN;
        for(int i = 0; i<n; i++)
        {
            if(tempSum < 0)
                tempSum = A[i]; //如果小于0,则前面的就都不要了
            else
                tempSum += A[i];
            
            ans = max(tempSum,ans);
        }
        return ans;
    }
};
原文地址:https://www.cnblogs.com/qingcheng/p/3873555.html