Skip to content

Instantly share code, notes, and snippets.

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

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

Select an option

Save pdu/4405242 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. 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. http://www.leetcode.com/onlinejudge
#include <algorithm>
using namespace std;
class Solution {
public:
int maxProfit(vector<int> &prices) {
int mini = 0x7fffffff;
int ret = 0;
for (int i = 0; i < prices.size(); ++i) {
ret = max(ret, prices[i] - mini);
mini = min(mini, prices[i]);
}
return ret;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment