Leetcode#121 Best Time to Buy and Sell Stock

原题地址

Best Time to Buy and Sell Stock III(参见这篇文章)的简化版

迭代法求最大利润。当然是在峰值卖出,在低谷买进利润最大了。所以从后向前遍历所有价格,如果当前价格比之前的峰值价格还高,更新峰值价格,否则就用峰值价格减去当前价格看看利润多少。

代码:

 1 int maxProfit(vector<int> &prices) {
 2         int profit = 0;
 3         int climax = -1;
 4         
 5         for (int i = prices.size() - 1; i >= 0; i--) {
 6             if (prices[i] >= climax)
 7                 climax = prices[i];
 8             else
 9                 profit = max(profit, climax - prices[i]);
10         }
11         
12         return profit;
13 }
原文地址:https://www.cnblogs.com/boring09/p/4262460.html