美文网首页
121. Best Time to Buy and Sell S

121. Best Time to Buy and Sell S

作者: 刘小小gogo | 来源:发表于2018-09-07 00:07 被阅读0次
    image.png
    class Solution {
    public:
        int maxProfit(vector<int>& prices) {
            if(prices.empty()) return 0;
            vector<int> dp(prices.size(), 0);
            dp[0] = 0;
            int max = dp[0];//用dp数组内的数来做初始值,防止[1]这种,而max = INT_MAX
            for(int i = 1; i < prices.size(); i++){
                for(int j = i - 1; j >= 0; j--){
                    if(prices[i] - prices[j] > dp[i])
                        dp[i] = prices[i] - prices[j];
                }
                if(dp[i] > max)
                    max = dp[i];
            }
            return max;
        }
    };
    
    class Solution {
    public:
        int maxProfit(vector<int>& prices) {
            int minx = INT_MAX;
            int diff = 0;
            for(int i = 0; i < prices.size(); i++){
                if(prices[i] < minx){
                    minx = prices[i];
                }
                diff = max(diff, prices[i] - minx);
            }
            return diff;
            
        }
    };
    

    相关文章

      网友评论

          本文标题:121. Best Time to Buy and Sell S

          本文链接:https://www.haomeiwen.com/subject/qinfgftx.html