Say you has an array for which the i t H element is the price of a given stock on day i .
Design an algorithm to find the maximum profit. You are in most of the transactions.
Note:
Engage in multiple transactions on the same time (ie, you must sell the stock before you buy again).
Thinking of solving problems
Create two arrays left
and right
store the maximum benefits that can be obtained from the left and right sides of an element, respectively. That is, left[i]
store the maximum benefit from the range and [0, i]
right[i]
store [i, len - 1]
The maximum benefit from the range.
Implementation code
/***************************************************************** * @Author: Chu hing * @Date: 2015/2/22 18 : @Status: Accepted * @Runtime: ms******************************************************************/< /c6>#include <iostream>#include <vector>#include <algorithm>using namespace STD;classSolution { Public:intMaxprofit ( vector<int>&prices) {intLen = Prices.size ();if(len = =0) {return 0; } vector<int>Left (Len,0); vector<int>Right (Len,0);inti =0;intLow = prices[0];intProfit =0; while(I < Len-1) {if(Prices[i] < low) {low = Prices[i]; }Else if(Prices[i] >= prices[i +1] {Profit = MAX (Profit, Prices[i]-low); } Left[i] = profit; i++; } Profit = Max (Profit, Prices[i]-low); LEFT[I] = profit;intHigh = prices[i]; Profit =0; while(I >0) {if(Prices[i] > High) {high = prices[i]; }Else if(Prices[i] <= prices[i-1] {Profit = MAX (profit, High-prices[i]); } Right[i] = profit; i--; } Profit = Max (profit, High-prices[i]); RIGHT[I] = profit; i =0;intMax_profit =0; while(I < Len) {max_profit = max (Max_profit, left[i] + right[i]); i++; }returnMax_profit; }};intMain () {intNum[] = {1,2,3,4,5,6}; vector<int>n (num, num +sizeof(num)/sizeof(int)); Solution S;intProfit = S.maxprofit (n);cout<<profit<<endl;}
[Leetcode] best time to Buy and Sell Stock III