LeetCode 121. 买卖股票的最佳时机(Best Time to Buy and Sell Stock)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/GreenHandCGL/article/details/83350679

简单粗暴的第一种解法:

class Solution {
public:
    int maxProfit(vector<int>& prices) {
        int m = prices.size();
        int maxprofit = 0;
        for (int k = 0; k < m; k++)
        {
            for (int i = k; i < m; i++){
                if (prices[i] - prices[k] > maxprofit)
                    maxprofit = prices[i] - prices[k];
            }
        }
        return maxprofit;
    }
};

第二种解法:

从最后一个元素开始遍历(vector不能为空),维持一个最大价格和一个最大收益

class Solution {
public:
    int maxProfit(vector<int>& prices) {
        int m = prices.size();
        if (m == 0) return 0;
        int maxprofit = 0;
        int maxprice = prices.back();
        for (int k = m-1; k >= 0; k--)
        {
            if (prices[k] > maxprice) maxprice = prices[k];
            else if(maxprice - prices[k] > maxprofit) maxprofit = maxprice - prices[k];
        }
        return maxprofit;
    }
};

猜你喜欢

转载自blog.csdn.net/GreenHandCGL/article/details/83350679