121. Best Time to Buy and Sell Stock 股票最佳买入和卖出时间

Input: [7,1,5,3,6,4]
Output: 5
Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.
             Not 7-1 = 6, as selling price needs to be larger than buying price.
在第2天 1元买入,在第5天 6元卖出,赚6-1=5元,为最大收益。

难度:【easy】

思路:

方法1:最开始最容易想到的是用暴力法解决,两层遍历,计算每个元素和它后面所有元素的差, 取最大的差,就是最大的收益。这种方法时间复杂度是O(n^2),空间O(1).

方法2:从后向前获取对于每个元素,在它后面元素的最大值。在用这个最大值和当前元素值计算收益。time:O(n),space:O(1)

class Solution {
public:
    int maxProfit(vector<int>& prices) {
        int max = 0;
        int max_profit = 0;
        int cur_profit = 0;
        for (int i = prices.size() - 2; i >= 0; --i) {
            if (max < prices[i + 1]) {
                max = prices[i + 1];
            }
            
            // 注意:这里每个元素都要计算和max的差
            cur_profit = max - prices[i];
            if (cur_profit > max_profit) {
                max_profit = cur_profit;
            }
        }
        
        return max_profit;
    }
};

方法3:相对于方法2,可以反过来,从前向后遍历,找到前面最小的元素,和当前元素进行比较。time:O(n),space:O(1)

    int maxProfit(vector<int>& prices) {
        if (prices.size() < 2) { return 0; }
        
        int min = prices[0];
        int max_profit = 0;
        
        for (int i = 1; i < prices.size(); ++i) {
            if (prices[i] < min) {
                min = prices[i];
            } else if (prices[i] - min > max_profit){
                max_profit = prices[i] - min;
            }
        }
        return max_profit;
    }

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值