188. 买卖股票的最佳时机IV

题目链接

解题思路:动态规划

使用一系列变量存储买入的状态,再用一系列变量存储卖出的状态。buy[j]表示恰好进行第j笔交易,并且当前手上持有一张股票,这种情况下的最大利润;sell[j]表示恰好进行第j笔交易,并且当前手上没有股票,这种情况下的最大利润。

C++:

#include <vector>
#include <limits>

using namespace std;

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

        int n = prices.size();
        k = min(k, n / 2);
        vector<int> buy(k + 1);
        vector<int> sell(k + 1);

        buy[0] = -prices[0];
        sell[0] = 0;
        for (int i = 1; i <= k; ++i) {
            buy[i] = sell[i] = numeric_limits<int>::min() / 2;
        }

        for (int i = 1; i < n; ++i) {
            buy[0] = max(buy[0], sell[0] - prices[i]);
            for (int j = 1; j <= k; ++j) {
                // buy[j]表示第i-1天持有一张股票,第i天仍然持有这张股票
                // sell[j] - prices[i]表示第i-1天没有持有股票,第i天买入了一张股票
                buy[j] = max(buy[j], sell[j] - prices[i]);
                // sell[j]表示第i-1天没有股票,第i天仍然没有买入股票
                // buy[j - 1] + prices[i]表示第i-1天有一张股票,第i天卖出了这张股票
                sell[j] = max(sell[j], buy[j - 1] + prices[i]);
            }
        }

        return *max_element(sell.begin(), sell.end());
    }
};

 

posted @ 2021-04-01 12:27  洗盏更酌  Views(53)  Comments(0Edit  收藏  举报