[Dynamic Programming Question 7] The best time to buy and sell stocks includes a freezing period&& The best time to buy and sell stocks includes handling fees

The best time to buy and sell stocks includes a freeze period

Link: The best time to buy and sell stocks including freeze period

Given an integer array prices, where prices[i] represents the stock price on day 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 (i.e. the freeze period is 1 day).
NOTE: You cannot participate in multiple trades at the same time (you must sell your previous shares before buying again).

Example 1:
Input: prices = [1,2,3,0,2]
Output: 3
Explanation: The corresponding transaction status is: [Buy, Sell, Freeze Period, Buy, Sell]

Example 2:
Input: prices = [1]
Output: 0

1. Status representation

For this kind of problem, our status representation generally has two forms:

  1. i. Starting from the position [i, j],...;
  2. ii. Starting from the starting position and arriving at the [i, j] position,...;

Here we choose a more common method, ending with a certain position, and defining a state representation based on the requirements of the topic: It can be seen that when
ending with a certain position, we can analyze three states :
Buy, tradable (stocks can be purchased), frozen

So we define a two-dimensional array:

  1. dp[i][0] means: after the end of the i-th day, it is in the "buy" state and the maximum profit at this time;
  2. dp[i][1] means: after the end of the i-th day, it is in the "tradable" state and the maximum profit at this time;
  3. dp[i][2] means: after the end of the i-th day, it is in the "freezing period" state, and the maximum profit at this time

2. State transition equation

Through the transfer methods between the three states, we can conclude that

Insert image description here
State transition equation:

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][2])
dp[i][2] = dp[i - 1][0] + prices[i]

3. Initialization

All three states will use the value of the previous position, so the first position of each row needs to be initialized:

  1. dp[0][0]: If you want to be in the "buy" state at this time, you must buy the stock on the first day, so dp[0][0] = -prices[0];
  2. dp[0][1]: Just use nothing, so dp[0][1] = 0;
  3. dp[0][2]: If you don’t have stocks in hand, you will be in the freezing period after buying and selling. At this time, the income is 0, so dp[0][2]= 0

4. The order of filling in the forms.
According to the "status display", we need to fill in three forms together, each form "from left to right".

5. Return value
Returns the maximum value in the three states

max(dp[0][n-1],max(dp[1][n-1],dp[2][n-1]))

Code:

int maxProfit(vector<int>& prices) {
    
    
        int n=prices.size();

        vector<vector<int>> dp(3,vector<int>(n));
        dp[0][0]=-prices[0];
        dp[1][0]=dp[2][0]=0;

        for(int i=1;i<n;i++)
        {
    
    
            dp[0][i]=max(dp[2][i-1]-prices[i],dp[0][i-1]);
            dp[1][i]=dp[0][i-1]+prices[i];
            dp[2][i]=max(dp[2][i-1],dp[1][i-1]);
        } 
        return max(dp[0][n-1],max(dp[1][n-1],dp[2][n-1]));
    }

Insert image description here

The best time to buy and sell stocks including fees

Link: The best time to buy and sell stocks including fees

Given an integer array prices, where prices[i] represents the stock price on day i; the integer fee represents the handling fee for trading stocks.

You can complete transactions an unlimited number of times, but you need to pay a fee for each transaction. If you have already purchased a stock, you cannot purchase any more shares until you sell it.

Returns the maximum value of profit obtained.

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

Example 1:
Input: prices = [1, 3, 2, 8, 4, 9], fee = 2
Output: 8
Explanation: The maximum profit that can be achieved:
buy here prices[0] = 1
sell here Bid prices[3] = 8
Buy here prices[4] = 4
Sell here prices[5] = 9
Total profit: ((8 - 1) - 2) + ((9 - 4) - 2 ) = 8

Example 2:
Input: prices = [1,3,7,5,10,3], fee = 3
Output: 6

1. Status representation

For this kind of problem, our status representation generally has two forms:

  1. i. Starting from the position [i, j],...;
  2. ii. Starting from the starting position and arriving at the [i, j] position,...;

Here we choose a more commonly used method, ending with a certain position, combined with the requirements of the topic, to define a state representation: the state
after the end of the i-th day.
It can be seen that when ending at a certain position, we can analyze two states:
buy, tradable (stocks can be purchased)

As can be seen from the question, the handling fee will only be deducted after a complete transaction, so we choose to deduct the handling fee after selling the stock.

So we define a two-dimensional array:

  1. dp[i][0] means: after the end of the i-th day, it is in the "buy" state and the maximum profit at this time;
  2. dp[i][1] means: after the end of the i-th day, it is in the "tradable" state and the maximum profit at this time;

2. State transition equation

By looking at the transition between two states, we can derive

Insert image description here

State transition equation:

dp[i][0] = max(dp[i - 1][0], dp[i - 1][1] -prices[i])
 dp[i][1]=max(dp[i-1][0]+prices[i]-fee,dp[i-1][1]);

3. Initialization

Since the previous state needs to be used, the first position needs to be initialized.
◦ For dp[i][0], it is in the "buy" state at this time, so dp[i0[0]= -prices[0]; ◦ For dp[
i][1], it is in the "no stock" state at this time In this state, you can get the maximum benefit by doing nothing, so dp[i][1]= 0.

4. The order of filling in the forms
is undoubtedly "from left to right", but the two forms need to be filled in together.

5. Return value
should return the maximum profit of the last day in the "Sell" state: dp[n-1][1];

Code:

  int maxProfit(vector<int>& prices, int fee) {
    
    
        int n=prices.size();

        vector<vector<int>> dp(n,vector<int>(2));

        dp[0][0]=-prices[0];//第一天手上有票
        dp[0][1]=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][0]+prices[i]-fee,dp[i-1][1]);
        }

        return dp[n-1][1];
    }

Insert image description here

Guess you like

Origin blog.csdn.net/m0_64579278/article/details/132199599