[leetcode] 53. Maximum Subarray

Posted zmj97

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[leetcode] 53. Maximum Subarray相关的知识,希望对你有一定的参考价值。

Find the contiguous subarray within an array (containing at least one number) which has the largest sum.

For example, given the array [-2,1,-3,4,-1,2,1,-5,4],
the contiguous subarray [4,-1,2,1] has the largest sum = 6


 

只要知道 除非全负,任何的负的子序列不可能是最优子序列的前缀 就可以了。

我的代码:

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

 


以上是关于[leetcode] 53. Maximum Subarray的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode 53. Maximum Subarray

leetcode 53. Maximum Subarray

Leetcode 53 Maximum Subarray

41. leetcode 53. Maximum Subarray

Leetcode53 Maximum Subarray

LeetCode练题——53. Maximum Subarray