day51 || ● 309. The best time to buy and sell stocks includes a freezing period ● 714. The best time to buy and sell stocks includes handling fees

Question 1: 309. The best time to buy and sell stocks includes a freezing period - LeetCode

Given an array of integers prices, where the th   represents   the stock price on the th day.  prices[i]i

Design an algorithm to calculate the maximum profit. You can complete as many transactions as possible (buy and sell a stock multiple times) subject to the following constraints:

  • After selling the stock, you cannot buy the stock the next day (that is, the freezing period is 1 day).

Note: You cannot participate in multiple transactions at the same time (you must sell the previous stock before buying again)

Idea: There is an extra cooling-off period for this question, which is more troublesome. The key lies in the description of the state. The code is as follows:

class Solution {
public:
    int maxProfit(vector<int>& prices) {
        int n = prices.size();
        if (n == 0) return 0;
        vector<vector<int>> dp(n, vector<int>(4, 0));
        dp[0][0] -= prices[0]; // 持股票
        for (int i = 1; i < n; i++) {
            dp[i][0] = max(dp[i - 1][0], max(dp[i - 1][3] - prices[i], dp[i - 1][1] - prices[i]));
            dp[i][1] = max(dp[i - 1][1], dp[i - 1][3]);
            dp[i][2] = dp[i - 1][0] + prices[i];
            dp[i][3] = dp[i - 1][2];
        }
        return max(dp[n - 1][3], max(dp[n - 1][1], dp[n - 1][2]));
    }
};

Question 2: 714. The best time to buy and sell stocks includes handling fees - LeetCode

Given an array of integers  prices, which  prices[i]represent  i the stock prices on the first day; the integers  fee represent the handling fees for trading stocks.

You can complete transactions an unlimited number of times, but you need to pay a transaction fee for each transaction. If you have already bought a stock, you cannot continue to buy another stock until you sell it.

Returns the maximum value of profit.

Note: A transaction here refers to the entire process of buying, holding and selling stocks, and you only need to pay a handling fee for each transaction.

Idea: There are more handling fees for this question, so we should think more about how to make a reasonable description. The specific code is as follows:

class Solution {
public:
    int maxProfit(vector<int>& prices, int fee) {
        int n = prices.size();
        vector<vector<int>> dp(n, vector<int>(2, 0));
        dp[0][0] -= prices[0]; // 持股票
        for (int i = 1; i < n; i++) {
            dp[i][0] = max(dp[i - 1][0], dp[i - 1][1] - prices[i]);
            dp[i][1] = max(dp[i - 1][1], dp[i - 1][0] + prices[i] - fee);
        }
        return max(dp[n - 1][0], dp[n - 1][1]);
    }
};

Guess you like

Origin blog.csdn.net/weixin_56969073/article/details/132612633