LintCode - Maximum Subarray - Greedy Algorithm

Posted lvbbg

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LintCode - Maximum Subarray - Greedy Algorithm相关的知识,希望对你有一定的参考价值。

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的主要内容,如果未能解决你的问题,请参考以下文章

lintcode-easy-Maximum Depth of Binary Tree

[LintCode] Maximum Subarray 最大子数组

[LintCode] Maximum Gap 求最大间距

lintcode-medium-Binary Tree Maximum Path Sum

[LintCode] Create Maximum Number 创建最大数

LintCode - Maximum Subarray - Greedy Algorithm