Maximum sub-segment and maximum stock purchase and sale plan

Source: Internet
Author: User

[-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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.