121. Best Time to Buy and Sell Stock

image.png
class Solution {
public:
    int maxProfit(vector& prices) {
        if(prices.empty()) return 0;
        vector 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& 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 Stock)