1. 程式人生 > >LeetCode 121. 買賣股票的最佳時機(Best Time to Buy and Sell Stock)

LeetCode 121. 買賣股票的最佳時機(Best Time to Buy and Sell Stock)

簡單粗暴的第一種解法:

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;
    }
};