码迷,mamicode.com
首页 > 其他好文 > 详细

53. Maximum Subarray

时间:2017-05-19 00:51:54      阅读:130      评论:0      收藏:0      [点我收藏+]

标签:mil   lan   div   make   tar   vector   update   ret   var   

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

标签:mil   lan   div   make   tar   vector   update   ret   var   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!