Topic:
given an array, the first element of it is the price of the first day of a given stock. If you are only allowed to complete a single trade (i.e. buy and sell a stock), design an algorithm to calculate the maximum profit you can get. Note that you cannot sell stocks before buying stocks. Example1: Enter: [7,1,5,3,6,4] Output:5Explanation: in section2Day (stock price =1) when buying, in the first5Day (stock price =6) When selling, the maximum Profit =6-1=5. Note that profit cannot be7-1=6because the sell price needs to be greater than the buy price. Example2: Enter: [7,6,4,3,1] Output:0explanation: In this case, no transaction is completed, so the maximum profit is0。
Problem Solving Ideas:
Use the day after minus the day before to get the next profit, and then convert the topic to the maximum number of sub-sequences and problems.
classSolution { Public: intMaxprofit (vector<int>&prices) {Vector<int>profit; intMaxres =0; intsum =0; for(inti =1; I < prices.size (); ++i) {profit.push_back (Prices[i]-prices[i-1]); } for(inti =0; i < profit.size (); + +i) {Sum+=Profit[i]; if(Sum >0) {Maxres=Max (sum,maxres); }Else{sum=0; } } returnMaxres; }};
Another solution, the price of the day minus the minimum value of the previous stock today:
classSolution { Public: intMaxprofit (vector<int>&prices) {Vector<int> Minleft (prices.size (),0); intres =0; if(Prices.size () <=0){ return 0; } intMinval =Int_max; for(inti =0; i < prices.size (); ++i) {Minval=min (minval,prices[i]); Minleft[i]=Minval; } for(inti =1; i < prices.size (); ++i) {Res= Max (prices[i]-minleft[i-1],res); } returnRes; }};
"Simple Algorithm" 34. The best time to buy and sell stocks