33.121. 买卖股票的最时机

思路

第一个确定是buyVal
第二个三种情况

  1. 大于等于buyVal,就把这个设置为saleVal
  2. 小于buyVal buyVal 改变为这个,继续遍历

错误思路

我的想法是:先把买的时机确定了,再确定卖的时机,分类讨论,实际操作过程中,有问题:就是它总是改变的这样设计的话,最好是拥有一个不变的

正确思路

把这个数组分为左右两部分,右边最大值减去左边最小值
1+9
2+8
3+7
……
4+6
9+1

class Solution {
public:
    int maxProfit(vector<int>& prices) {
        int inf = 1e9;
        int minprice = inf, maxprofit = 0;
        for (int price: prices) {
            maxprofit = max(maxprofit, price - minprice);
            minprice = min(price, minprice);
        }
        return maxprofit;
    }
};

作者:LeetCode-Solution
链接:https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock/solution/121-mai-mai-gu-piao-de-zui-jia-shi-ji-by-leetcode-/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

我的

class Solution {
public:
    int maxProfit(vector<int>& prices) {
        int maxProfit = 0;
        int leftMin = prices[0];
        for(int i=1;i<prices.size();i++){
            if(prices[i] < leftMin){
                leftMin = prices[i];
            }
            maxProfit = max(maxProfit,prices[i] - leftMin);
        }
        return maxProfit;
    }    
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值