Created
December 29, 2012 07:48
-
-
Save pdu/4405281 to your computer and use it in GitHub Desktop.
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 …
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
| class Solution { | |
| public: | |
| int maxProfit(vector<int> &prices) { | |
| int ret = 0; | |
| int buy = 0x7fffffff; | |
| int sell = -1; | |
| for (int i = 0; i < prices.size(); ++i) { | |
| if (sell == -1) { | |
| if (prices[i] <= buy) { | |
| buy = prices[i]; | |
| } | |
| else { | |
| sell = prices[i]; | |
| } | |
| } | |
| else { | |
| if (prices[i] >= sell) { | |
| sell = prices[i]; | |
| } | |
| else { | |
| ret += sell - buy; | |
| buy = prices[i]; | |
| sell = -1; | |
| } | |
| } | |
| } | |
| if (sell != -1) { | |
| ret += sell - buy; | |
| } | |
| return ret; | |
| } | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment