美文网首页
leetcode123 & 309 & 714 买卖股票最佳时机

leetcode123 & 309 & 714 买卖股票最佳时机

作者: 奥利奥蘸墨水 | 来源:发表于2019-12-30 22:50 被阅读0次

两次

class Solution {
public:
    int maxProfit(vector<int>& prices){
        return maxProfit_k_times(2,prices);
    }

    int maxProfit_k_times(int k_max, vector<int>& prices) {

        if (prices.empty()){
            return 0;
        }

        int len = prices.size();

        if (k_max > len / 2){
            return maxProfit_infinity(prices);
        }

        vector<vector<vector<int>>> dp(len, vector<vector<int>>(k_max + 1, vector<int>(2, 0)));

        for (int i = 0; i < len; i++){
            for (int k = 1; k <= k_max; k++){
                if (i == 0){
                    dp[i][k][0] = 0;
                    dp[i][k][1] = -prices[i];
                }else{
                    dp[i][k][0] = max(dp[i - 1][k][0], dp[i - 1][k][1] + prices[i]);
                    dp[i][k][1] = max(dp[i - 1][k][1], dp[i - 1][k - 1][0] - prices[i]);
                }
            }
        }

        return dp[len - 1][k_max][0];
    }

    int maxProfit_infinity(vector<int>& prices){
        int cur_min = INT_MAX, cur_profit = 0, res = 0;

        for (auto x : prices){
            if (x - cur_min > cur_profit){
                cur_profit = x - cur_min;
            }else{
                res += cur_profit;
                cur_profit = 0;
                cur_min = x;
            }
        }

        return res + cur_profit;
    }
};

冷冻期

class Solution {
public:
    int maxProfit(vector<int>& prices) {
        if (prices.empty()){
            return 0;
        }

        int len = prices.size();

        vector<vector<int>> dp(len, vector<int>(2, 0));

        for (int i = 0; i < len; i++){
            if (i == 0){
                dp[i][0] = 0;
                dp[i][1] = -prices[i];
            }else{
                dp[i][0] = max(dp[i - 1][0], dp[i - 1][1] + prices[i]);
                
                if (i >= 2)
                    dp[i][1] = max(dp[i - 1][1], dp[i - 2][0] - prices[i]);
                else
                    dp[i][1] = max(dp[i - 1][1], dp[i - 1][0] - prices[i]);
            }

            // cout << dp[i][0] << " " << dp[i][1] << endl;
        }

        return dp[len - 1][0];
    }
};

手续费

class Solution {
public:
    int maxProfit(vector<int>& prices, int fee) {
        if (prices.empty()){
            return 0;
        }

        int len = prices.size();

        vector<vector<int>> dp(len, vector<int>(2, 0));

        for (int i = 0; i < len; i++){
            if (i == 0){
                dp[i][0] = 0;
                dp[i][1] = -prices[i];
            }else{
                dp[i][0] = max(dp[i - 1][0], dp[i - 1][1] + prices[i] - fee);
                dp[i][1] = max(dp[i - 1][1], dp[i - 1][0] - prices[i]);
            }
        }

        return dp[len - 1][0];
    }
};

相关文章

网友评论

      本文标题:leetcode123 & 309 & 714 买卖股票最佳时机

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