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
.
题意:在数组中,查找一个连续的子数组,使它的元素有最大和,求最大和
分类:数组,动态规划
解法1:很经典的动态规划题目。关键是找到规划关系。
设flag[i],我们知道,每个子数组,都必然以一个元素结尾,所有flag[i]就代表,以元素nums[i]为结尾的子数组的最大和
那么来考虑flag[i+1],对于它只有两种选择,一个是nums[i+1],一个是nums[i+1]+flag[i]
所以关系就是flag[i+1]=Max(nums[i+1],nums[i+1]+flag[i]);
原文链接http://blog.youkuaiyun.com/crazy__chen/article/details/46389573