121. Best Time to Buy and Sell S

2018-09-07  本文已影响0人  刘小小gogo
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;
        
    }
};
上一篇 下一篇

猜你喜欢

热点阅读