Leetcode:53. Maximum Subarray

Description

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

Example

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 len = nums.size();
        if(len == 0) return INT_MIN;
        
        int res = nums[0], sum = 0;
        for(int i = 0; i < len; ++i){
            sum += nums[i];
            
            if(res < sum)
                res = sum;
                
            if(sum < 0) 
                sum = 0;
        }
        
        return res;
    }
};
posted @ 2017-05-15 18:23  JeffLai  阅读(88)  评论(0编辑  收藏  举报