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.
思路:
逆序搜索,第i天买入的股票所能得的最大利润为第i+1到第n天的最大股票价格。
代码:
int maxProfit(vector<int> &prices) {
int len=prices.size();
if (len == 0)
return 0;
int maxPrice = prices[len-1];
int maxPro = 0;
for(int i = len - 1; i >= 0; i--)
{
maxPrice = max(maxPrice, prices[i]);
maxPro = max(maxPro, maxPrice - prices[i]);
}
return maxPro;
}