LeetCode188 买卖股票的最佳时机 IV(dp)

LeetCode188 买卖股票的最佳时机 IV

对于第 \(i\) 只股票,可以进行的操作为作为第 \(j\) 只买入或卖出的股票

\(buy[i][j]\) 表示对于前 \(i\) 只股票,第 \(j\) 次买入股票之后的最大收益

\(sell[i][j]\) 表示对于前 \(i\) 只股票,第 \(j\) 次卖出股票之后的最大收益

\(j\) 次买入股票必须在第 \(j - 1\) 次卖出股票之后发生

这里可以使用滚动数组,优化空间复杂度

class Solution:
    def maxProfit(self, k: int, prices: List[int]) -> int:

        if len(prices) == 0: return 0
        if k == 0: return 0

        buy, sell, l = [-prices[0]] * k, [0] * k, len(prices)

        for i in range(1, l):
            for j in range(k):
                if j == 0:
                    buy[j] = max(buy[j],  -prices[i])
                    sell[j] = max(sell[j], prices[i] + buy[j])
                else:
                    buy[j] = max(buy[j],  sell[j - 1] - prices[i])
                    sell[j] = max(sell[j], prices[i] + buy[j])

        return sell[k - 1]
class Solution {
public:
    int maxProfit(int k, vector<int>& prices) {
        if (prices.empty()) return 0;
        if (k == 0) return 0;

        int n = prices.size();
        vector<int> buy(k);
        vector<int> sell(k);
        
        for (int i = 0; i < k; ++i) {
            buy[i] = -prices[0], sell[i] = 0;
        }

        for (int i = 1; i < n; ++i) {
            for (int j = 0; j < k; ++j) {
                if (j == 0) {
                    buy[j] = max(buy[j], -prices[i]);
                    sell[j] = max(sell[j], buy[j] + prices[i]);
                } else {
                    buy[j] = max(buy[j], sell[j - 1] - prices[i]);
                    sell[j] = max(sell[j], buy[j] + prices[i]);
                }
            }
        }
        return sell[k - 1];
    }
};

posted on 2022-06-29 16:16  solvit  阅读(22)  评论(0编辑  收藏  举报

导航