首页 > 其他 > 详细

53. Maximum Subarray

时间:2017-05-19 00:37:49      阅读:368      评论:0      收藏:0      [点我收藏+]

Problem statement:

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.

Solution:

The problem wants the max sum of a subarray. The basic idea is to drop the array if its sum is negative.

There two variables: one is the current sum, another is the max sum. The idea is similar with 300. Longest Increasing Subsequence

Time complexity is O(n).

class Solution {
public:
    int maxSubArray(vector<int>& nums) {
        int cur_sum = 0;
        int max_sum = INT_MIN;
        for(auto num : nums){
            if(cur_sum < 0){
                // cur_sum < 0, drop off it and make cur_sum = num
                cur_sum = num;
            } else {
                // if cur_sum >= 0, add num to cur_sum
                cur_sum += num;
            }
            // update the max sum for each element
            max_sum = max(max_sum, cur_sum);
        }
        return max_sum;
    }
};

 

53. Maximum Subarray

原文:http://www.cnblogs.com/wdw828/p/6876208.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!