[-2,2,3,-1]的最大字段和是[2,3]/*动态规划算法:**b[j]=max{a[i]+ +a[j]},1<=i<=j,且1<=j<=n,则所求的最大子段和为max b[j],1<=j<=n。**由b[j]的定义可易知,当b[j-1]>0时b[j]=b[j-1]+a[j],否则b[j]=a[j]。故b[j]的动态规划递归式为:**b[j]=max(b[j-1]+a[j],a[j]),1<=j<=n。**T(n)=O(n)*/int MaxSum_DYN(int *v,int n){ int sum=0,b=0; int i; for (i=1;i<=n;i++) { if(b>0) b+=v[i]; else b=v[i]; if(b>sum) sum=b; } return sum;}
There is a stock problem:
Given an int array with a length of N, the array stores the price of a stock for N days, seeking for the most profitable Purchase and SaleOut of the solution, such as [, 6], then when you buy 7 at 2, you can make the maximum profit.
for(i = 0; i < n; ++i){ minPrice = min(minPrice, a[i]); best = max(a[i] - minPrice, best);}Or the price change array is [-2, 3, 2,-1], followed by the largest sub-segment and question.
Maximum sub-segment and maximum stock purchase and sale plan