Leetcode: Best Time to Buy and Sell Stock I II III
Best Time to Buy and Sell Stock I
Say you have an array for which the ith element is the price of a given stock on day i.
If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.
1 int maxProfit(vector<int> &prices) { 2 // Start typing your C/C++ solution below 3 // DO NOT write int main() function 4 if (prices.size() == 0) 5 return 0; 6 7 int low = prices[0]; 8 int profit = 0; 9 10 for (int i = 1; i < prices.size(); ++i) 11 { 12 low = min(prices[i], low); 13 profit = max(profit, prices[i] - low); 14 } 15 16 return profit; 17 }
class Solution { public: int maxProfit(vector<int> &prices) { if(prices.size() < 2) return 0; int cl = INT_MAX, maxp = 0; for(vector<int>::iterator i = prices.begin(); i != prices.end(); ++i) { cl = min(cl, *i); maxp = max(maxp, *i-cl); } return maxp; } };
Best Time to Buy and Sell Stock II
Say you have an array for which the ith element is the price of a given stock on day i.
Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
1 class Solution { 2 public: 3 int maxProfit(vector<int> &prices) { 4 // Start typing your C/C++ solution below 5 // DO NOT write int main() function 6 int p = 0; 7 for (int i = 1; i < prices.size(); i++) 8 { 9 int delta = prices[i] - prices[i-1]; 10 if (delta > 0) 11 p += delta; 12 13 } 14 return p; 15 } 16 };
1 class Solution { 2 3 public: 4 int maxProfit(vector<int> prices) 5 { 6 if( prices.size() < 2) 7 return 0; 8 9 int maxProfit = 0; 10 11 for(int i = 1; i < prices.size(); i++){ 12 if(prices[i] > prices[i - 1]) 13 maxProfit += prices[i] - prices[i - 1]; 14 } 15 return maxProfit; 16 17 } 18 };
Best Time to Buy and Sell Stock III
Say you have an array for which the ith element is the price of a given stock on day i.
Design an algorithm to find the maximum profit. You may complete at most two transactions.
Note:
You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
First consider the case that when we are only allowed to make one transaction. we can handle this easily with DP. If we move forward, any new price we meet will only affect our history result by two ways:
- will it be so low that it beats our previous lowest price?
- will it be so high that we should instead sell on this time to gain a higher profit (than the history record)? Similarly, we can move backward with the highest price and profit in record. Either way would take O(n) time.
Now consider the two transaction case. Since there will be no overlaps, we are actually dividing the whole time into two intervals.
We want to maximize the profit in each of them so the same method above will apply here. We are actually trying to break the day at each time instance, by adding the potential max profit before and after it together. By recording history and future for each time point, we can again do this within O(n) time.
1 class Solution { 2 public: 3 int maxProfit(vector<int> &prices) { 4 // null check 5 int len = prices.size(); 6 if (len==0) return 0; 7 8 vector<int> historyProfit; 9 vector<int> futureProfit; 10 historyProfit.assign(len,0); 11 futureProfit.assign(len,0); 12 int valley = prices[0]; 13 int peak = prices[len-1]; 14 int maxProfit = 0; 15 16 // forward, calculate max profit until this time 17 for (int i = 0; i<len; ++i) 18 { 19 valley = min(valley,prices[i]); 20 if(i>0) 21 { 22 historyProfit[i]=max(historyProfit[i-1],prices[i]-valley); 23 } 24 } 25 26 // backward, calculate max profit from now, and the sum with history 27 for (int i = len-1; i>=0; --i) 28 { 29 peak = max(peak, prices[i]); 30 if (i<len-1) 31 { 32 futureProfit[i]=max(futureProfit[i+1],peak-prices[i]); 33 } 34 maxProfit = max(maxProfit,historyProfit[i]+futureProfit[i]); 35 } 36 return maxProfit; 37 } 38 };
A new problem of completing at most m transactions can be efficiently solved by using the method below.
The profit of one transaction is price[i]-price[j]
where i > j
. We then can rewrite the expression to be: price[i]-price[i-1] + price[i-1]-price[i-2] + ... + price[j+1]-price[j]
. If we construct an array of {diff[i]} = {price[i+1]-price[i]}
, then the problem can be reduced to the maximum m segments sum problem on diff[]
, where m = 2
in this case. Then we can play the fancy dynamic programming to solve it.
Here is one solution of the maximum m segments sum problem. The running time is O(NM).
Let f[i][j]
to be the maximum sum of j
segments from the first i
numbers, where the last element we choose is a[i]
. We have two strategies to achieve it:
- Choosing the optimal
j-1
segments from the firstk
numbers, and starting a new segment witha[i]
:
f[i][j] = f[k][j-1] + a[i], where j-1 <= k <= i-1.
However, f[k][j-1]
is the subproblems that we've already solved. If we memorize the optimal j-1
segments, namely g[j-1] = max(f[k][j-1])
, the state transition can be achieved in O(1):
f[i][j] = g[j-1] + a[i]
- Appending
a[i]
to the last segment in the firsti-1
numbers
f[i][j] = f[i-1][j] + a[i].
Here is why we must choose a[i]
in our strategies. If f[i-1][j]
is not ends at a[i-1]
, then appending a[i]
to f[i-1][j]
will get j+1
segments, which violates the definition of f[i][j]
.
1 class Solution { 2 public: 3 int maxProfit(vector<int> &prices) { 4 int f[3] = {0}; 5 int g[3] = {0}; 6 7 int n = prices.size() - 1; 8 for (int i = 0; i < n; ++i) { 9 int diff = prices[i+1] - prices[i]; 10 int m = min(i+1, 2); 11 for (int j = m; j >= 1; --j) { 12 f[j] = max(f[j], g[j-1]) + diff; 13 g[j] = max(g[j], f[j]); 14 } 15 } 16 return max(g[1], g[2]); 17 } 18 };