On the biggest gains in commodity trading

Source: Internet
Author: User

Given a sequence such as "2,4,7,8,7,10,5", for a product we can choose "buy" "sell" "Give up" three kinds of operation.

But they have to follow the order of "buy" and "sell" .

Problem Description:

    1. Do not limit the number of transactions, how to obtain the maximum income, the maximum amount of income;
    2. What is the maximum benefit of trading only once?
    3. What is the maximum benefit of trading only two times;

Question One

The array is processed to make diff=nums[i]-nums[i-1]; as long as the diff>0, it will be added to the final result;

2+3+1+3=9, i.e. "2,8" "7,10"

The code is as follows:

intMaxsum (int*pnum,intLen) {    if(NULL = = Pnum)return 0; if(1= Len)return 0; intRET =0; intdiff =0;  for(inti =1; i < Len; ++i) {diff= Pnum[i]-pnum[i-1]; if(diff >0) {ret+=diff; }    }    returnret;}

Question Two

To regenerate a sequence according to Nums[i]-nums[i-1], only one transaction is equivalent to the maximal contiguous sub-segment of the novelty sequence;

2+3+1+ (-1) +3=8, or "2,10"

The code is as follows:

intGetdis (intA[],intN) {    //Write code here    intMaxdis =0; intdis =0;  for(inti =1; I < n; ++i) {if(Dis >=0) {dis+ = A[i]-a[i-1]; }        Else{dis= A[i]-a[i-1]; } Maxdis=max (Maxdis, dis); }    returnMaxdis;}

Question Three

Here's my idea: on the basis of question two, add a layer of loops to control the division of the sequence into two parts. Then the left and right part of the operation of the problem two, the two parts of the maximum value of the sum as the maximum benefit of the whole sequence.

According to the different division of the interval, to find out the greatest benefit;

6+3=9, i.e. "2,8" "7,10"

Because the code is relatively simple, it is no longer detailed here.

On the biggest gains in commodity trading

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.