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

LintCode - Maximum Subarray - Greedy Algorithm

时间:2017-10-20 12:01:41      阅读:114      评论:0      收藏:0      [点我收藏+]

标签:bar   write   ++   sum   color   you   class   log   logs   

Maximum Subarray

Given an array of integers, find a contiguous subarray which has the largest sum.

 

Given the array [?2,2,?3,4,?1,2,1,?5,3], the contiguous subarray [4,?1,2,1] has the largest sum = 6

 

class Solution {
public:
    /**
     * @param nums: A list of integers
     * @return: A integer indicate the sum of max subarray
     */
    int maxSubArray(vector<int> nums) {
        // write your code here
        int n = nums.size();
        int ans = -1000000;
        int sum = 0;
        for(int i=0; i<n; i++)
        {
            sum += nums[i];
            if(sum > ans)
            {
                ans = sum;
            }
            if(sum < 0)
            {
                sum = 0;   //子串和为负数,丢掉
            }
        }
        return ans;
    }
};

 

LintCode - Maximum Subarray - Greedy Algorithm

标签:bar   write   ++   sum   color   you   class   log   logs   

原文地址:http://www.cnblogs.com/xumh/p/7698360.html

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