题意要求只能买卖一次彩票。
从后向前遍历,记录i+1, i+2, ..., n中的最大值,计算prices[i]和最大值的差,更新最大利润。
代码:
class Solution
{
public:
int maxProfit(vector<int> &prices)
{
if(prices.empty())
{
return 0;
}
int max_price = prices.back();
int max_profit = 0;
for (int i = int(prices.size())-1; i >= 0; -- i)
{
max_price = max(max_price, prices[i]);
max_profit = max(max_profit, max_price-prices[i]);
}
return max_profit;
}
};