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.
This file contains 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) { | |
if(prices.empty()) | |
return 0; | |
int curLow=prices[0]; | |
int curProfit=0; | |
for(int i=0; i<prices.size(); i++){ | |
curProfit=prices[i]-curLow > curProfit? prices[i]-curLow: curProfit; | |
curLow=prices[i]<curLow? prices[i]:curLow; | |
} | |
return curProfit; | |
} | |
}; |
No comments:
Post a Comment