Skip to content

Instantly share code, notes, and snippets.

@pdu
Created December 29, 2012 07:48
Show Gist options
  • Select an option

  • Save pdu/4405281 to your computer and use it in GitHub Desktop.

Select an option

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 …
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