首页 > 其他 > 详细

LintCode - Maximum Subarray - Greedy Algorithm

时间:2017-10-20 11:36:18      阅读:215      评论:0      收藏:0      [点我收藏+]

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

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

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