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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值