Last active
December 6, 2018 10:40
-
-
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.
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 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