Say you have an array for whichITh element is the price of a given stock on dayI.
If you were only permitted to complete at most one transaction (ie, buy one and every one share of the stock), design an algorithm to find the maximum profit.
Idea: the solution to this problem, I think of dynamic planning, for example, to find the maximum benefit of day I, if I day stock price is greater than or equal to the day of the I-1, so Max [I] = MAX [I-1] + A [I]-A [I-1]; he can be the best benefit of the day of I-1;
When the price of the day I is less than the day of the I-1, this time to see the stock price a few days ago, find the first price less than the day I, set to the day J, then: max [I] = MAX [J] + A [I]-A [J]; it can be seen that the solution of this problem conforms to the optimal sub-structure nature and the characteristics of dynamic planning, therefore, you can use dynamic planning to solve the problem. The Code is as follows:
<I also see a way on the Internet, but also the use of dynamic planning, but he recorded the previous I day the lowest price one day, and the previous I-1 day the biggest benefit, when scanning the day I, compare the biggest benefit of the previous day and the difference between the price of the day I and the lowest price of the previous day, the biggest benefit of day I (the code is very concise and not provided here)>
1 class Solution { 2 public: 3 vector<int> max; 4 int maxProfit(vector<int> &prices) { 5 int maxx=0; 6 if(prices.size()<=1) return 0; 7 max.push_back(0); 8 for(int i=1;i<prices.size();i++) 9 {10 if(prices[i]>prices[i-1]) 11 {12 if(maxx<max[i-1]+prices[i]-prices[i-1])13 {14 maxx=max[i-1]+prices[i]-prices[i-1];15 }16 max.push_back(max[i-1]+prices[i]-prices[i-1]);17 18 19 }20 else21 {22 int j=prelow(prices,i);23 if(j==-1)24 {25 max.push_back(0);26 }27 else28 {29 if(maxx<max[j]+prices[i]-prices[j])30 {31 maxx=max[j]+prices[i]-prices[j];32 }33 max.push_back(max[j]+prices[i]-prices[j]);34 35 }36 }37 }38 return maxx;39 }40 41 int prelow(vector<int> &prices,int i)42 {43 for(int j=i-1;j>=0;j--)44 {45 if(prices[j]<=prices[i])46 {47 return j;48 }49 }50 return -1;51 }52 };
Best time to buy and stock Stock <leetcode>