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:
- Do not limit the number of transactions, how to obtain the maximum income, the maximum amount of income;
- What is the maximum benefit of trading only once?
- 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