Skip to content

Instantly share code, notes, and snippets.

@qiaoxu123
Last active December 6, 2018 10:40
Show Gist options
  • Save qiaoxu123/b047fbce1d5e11714ae26757d444e933 to your computer and use it in GitHub Desktop.
Save qiaoxu123/b047fbce1d5e11714ae26757d444e933 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 (i.e., buy one and sell one share of the stock), design an algorithm to find the maximum profit.
class Solution {
public:
int maxProfit(vector<int>& prices) {
int maxPro = 0;
int minPrice = INT_MAX;
for(int i = 0;i < prices.size();i++){
minPrice = min(minPrice,prices[i]);
maxPro = max(maxPro,prices[i] - minPrice);
}
return maxPro;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment