您好,欢迎来到二三四教育网。
搜索
您的当前位置:首页122. Best Time to Buy and Sell S

122. Best Time to Buy and Sell S

来源:二三四教育网

最开始股票需要先买后卖

题解:

  1. suppose the first sequence is "a <= b <= c <= d", the profit is "d - a = (b - a) + (c - b) + (d - c)";
  2. suppose another one is "a <= b >= b' <= c <= d", the profit is not difficult to be figured out as "(b - a) + (d - b')";
    所以只需要考虑递增序列

AC代码:

public:
    int maxProfit(vector<int>& prices) {
        
        int sum =0;       
        for(int i=1; i<prices.size(); i++){
            if(prices[i] > prices[i-1]){
                sum += prices[i] - prices[i-1];
            }
        }
        
        return sum;
    }

RE代码:

public:
    int maxProfit(vector<int>& prices) {
        
        int sum =0;     
        for(int i=0; i<prices.size()-1; i++){
            if(prices[i] < prices[i+1]){
                sum += prices[i+1] - prices[i];
            }
        }
        
        return sum;
    }

Copyright © 2019- how234.cn 版权所有 赣ICP备2023008801号-2

违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务