53. Maximum Subarray

53. Maximum Subarray

My Submissions
Question
Total Accepted: 89899  Total Submissions: 253014  Difficulty: Medium

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.

click to show more practice.

Subscribe to see which companies asked this question

Hide Tags
  Divide and Conquer Array Dynamic Programming
Show Similar Problems


分析:

典型的动态规划问题:

定义子问题:tmpSum[i]为以第i个元素结尾的最大连续子数组和
很显然在for循环遍历的过程中,只有两种情况:

1)tmpSum[i]重新以当前元素nums[i]开始

2)tmpSum[i]继续累加,即当前元素nums[i]+tmpSum[i-1]

在这里,实际上可以将tmpSum数组省去,直接用一个变量递推即可,因为只和前一次结果相关。

通俗的理解就是:

在加上当前nums[i]之前,如果tmpSum是小于0的,那么说明tmpSum起副作用,需要重新寻找起始数开始累加,

即重新以当前nums[i]为起始值开始累加,

class Solution {
public:
    int maxSubArray(vector<int>& nums) {
        int maxSum=INT_MIN,tmpSum=0;
        for(int i=0;i<nums.size();i++)
        {
            tmpSum=max(tmpSum+nums[i],nums[i]);//连续累加时的两种情况
            maxSum=max(maxSum,tmpSum);//更新最大值
        }
        return maxSum;
    }
};



注:本博文为EbowTang原创,后续可能继续更新本文。如果转载,请务必复制本条信息!

原文地址:http://blog.csdn.net/ebowtang/article/details/50422224

原作者博客:http://blog.csdn.net/ebowtang

你可能感兴趣的:(LeetCode,数据结构,算法,面试,ACM)