Permalink
Switch branches/tags
Nothing to show
Find file Copy path
Fetching contributors…
Cannot retrieve contributors at this time
23 lines (19 sloc) 677 Bytes
problem:
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.
--------------------------------------------------------
solution:
//第i天买入,能赚的利润是[i+1 ~ n中最大股价]- 第i天股价
int maxProfit(vector<int> &prices)
{
if(prices.size() == 0)
return 0;
int maxPrice = prices[prices.size() - 1];
int ret = 0;
for(int i = prices.size() - 1; i >= 0; i--)
{
maxPrice = max(maxPrice, prices[i]);
ret = max(ret, maxPrice - prices[i]);
}
return ret;
}