Last active
June 1, 2016 15:18
-
-
Save sundeepblue/10489990 to your computer and use it in GitHub Desktop.
best time to buy and sell stock. max profit.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| http://blog.unieagle.net/2012/12/04/leetcode%E9%A2%98%E7%9B%AE%EF%BC%9Abest-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. | |
| 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. | |
| */ | |
| int max_profit(const vector<int> &prices) { | |
| if(prices.empty() || prices.size() == 1) | |
| return 0; | |
| int maxp = 0, curr_min = prices[0]; | |
| for(int i=1; i<prices.size(); ++i) { | |
| curr_min = min(curr_min, prices[i]); | |
| maxp = max(maxp, prices[i] - curr_min); | |
| } | |
| return maxp; | |
| } | |
| /* | |
| 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). | |
| */ | |
| int max_profit_two_transaction(const vector<int> &prices) { | |
| if(prices.empty()) return 0; | |
| int N = prices.size(); | |
| vector<int> from_left(N, 0); | |
| int maxp_left = 0, curr_min = prices[0]; | |
| for(int i=1; i<N; ++i) { | |
| curr_min = min(curr_min, prices[i]); | |
| from_left[i] = max(from_left[i-1], prices[i] - curr_min); | |
| } | |
| vector<int> from_right(N, 0); | |
| int maxp_right = 0, curr_min = prices[N-1]; | |
| for(int i=N-2; i>=0; --i) { | |
| curr_min = min(curr_min, prices[i]); | |
| from_right[i] = max(from_right[i+1], prices[i] - curr_min); | |
| } | |
| int maxp = 0; | |
| for(int i=0; i<N; ++i) { // should start from 0 to N-1 | |
| maxp = max(maxp, from_left[i] + from_right[i]); | |
| } | |
| return maxp; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment