Maximum Subarray
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
.
/*
*动态规划:
*遍历数组每一个A[i],两种选择:1.加入前面的SubArray,2.从当前开始建立新SubArray;
*如果前面SubArray和大于0,那么对当前有贡献,应该加入;
*如果前面SubArray和小于等于0,那么对当前没有贡献或负面影响,应该新开SubArray
* 状态转移方程;
* d[i]=max(d[i]+A[i],A[i])
* target=max(d[i])
*
*
* */
class Solution{
public:
int maxSubArray(int A[],int n){
int ret=A[0];
int *d=(int *)malloc(n*sizeof(int));
d[0]=A[0];
for(int i=1;i<n;++i)
{
d[i]=max(A[i],d[i-1]+A[i]);
if(d[i]>ret)
ret=d[i]; //找出最大的
}
free(d);
return ret;
}
};
学习了 https://gitcafe.com/soulmachine/LeetCode 相关内容