【LeetCode】Dynamic programming training (5)

Sword Pointer Offer II 091. Paint the house

Click to view: Paint the house


Suppose there are n houses in a row, and each house can be painted in one of three colors: red, blue, or green. You need to paint all the houses and make the two adjacent houses not have the same color.
Of course, because the prices of different colors of paint on the market are different, the cost of painting a house in different colors is also different. The cost of painting each house in different colors is represented by an nx 3 positive integer matrix costs.
For example, costs[0][0] represents the cost of painting house No. 0 red; costs[1][2] represents the cost of painting house No. 1 green, and so on.
Please calculate the minimum cost to paint all the houses.

Example 1:
Input: costs = [[17,2,17],[16,16,5],[14,3,19]]
Output: 10
Explanation: Paint house 0 blue and paint house 1 painted green and house number 2 painted blue.
Minimum cost: 2 + 5 + 3 = 10.

topic analysis

The abscissa of the cost array represents the house number N, and the ordinate represents the color. Select
a color for each house, but the same color cannot be selected between adjacent houses. Find the minimum cost


insert image description here

The same color cannot be selected between neighbors, so after house No. 0 selects blue, house No. 1 cannot select blue.
Similarly, after house No. 1 selects green, house No. 2 cannot select green.
The minimum cost is 2+5 +3=10

state transition equation

When reaching the i position, there are three situations, red when the subscript is 0, blue when the subscript is 1, and green when the subscript is 2

dp[i][0]: indicates that when painting to position i, the last position is painted red, and the minimum cost at this time
dp[i][1]: indicates that when painting reaches position i, the last position is painted blue Color, the minimum cost at this time
dp[i][2]: means that when painting to position i, the last position is painted green, the minimum cost at this time


When position i is painted red, if you want to find the minimum cost in the interval [0,i], you should first find the minimum cost in the interval [0,i-1] because adjacent houses cannot have the same
color , so the i-1 position can only be blue or green
If the i-1 position is blue, then the minimum cost of the interval [0,i-1] is dp[i-1][1]
If the i-1 position is green , then the minimum cost in the interval [0,i-1] is the minimum value of dp[i-1][2]
, plus the cost at position i is the cost in the interval [0,i]

The state transition equation is:
dp[i][0]= min(dp[i-1][1],dp[i-1][2])+costs[i][0];


When position i is painted blue, if you want to find the minimum cost in the interval [0,i], you should first find the minimum cost in the interval [0,i-1] because adjacent houses cannot take the
same Color, so the i-1 position can only be red or green
If the i-1 position is red, the minimum cost of the [0,i-1] interval is dp[i-1][0]
If the i-1 position is green, Then the minimum cost in the interval [0,i-1] is
the minimum value of dp[i-1][2], plus the cost at position i is the cost in the interval [0,i]

The state transition equation is:
dp[i][1]= min(dp[i-1][0],dp[i-1][2])+costs[i][1];


When position i is painted green, if you want to find the minimum cost in the interval [0,i], you should first find the minimum cost in the interval [0,i-1] because adjacent houses cannot take the same
color , so the i-1 position can only be red or blue.
If the i-1 position is red, the minimum cost of the [0,i-1] interval is dp[i-1][0]
If the i-1 position is green, Then the minimum cost in the interval [0,i-1] is the minimum value of dp[i-1][1]
, plus the cost at position i is the cost in the interval [0,i]

The state transition equation is:
dp[i][2]= min(dp[i-1][0],dp[i-1][1])+costs[i][2];

full code

class Solution {
    
    
public:
    int minCost(vector<vector<int>>& costs) {
    
    
             
             int n=costs.size();
             //扩列 一行
             // 将 n+1个 vector数组 的3个数 都初始化为0
            vector<vector<int>>dp(n+1,vector<int>(3,0));
            int i=0;
            for(i=1;i<=n;i++)
            {
    
    
                //状态转移方程
                  dp[i][0]=min(dp[i-1][1],dp[i-1][2])+costs[i-1][0];
                  dp[i][1]=min(dp[i-1][0],dp[i-1][2])+costs[i-1][1];
                  dp[i][2]=min(dp[i-1][0],dp[i-1][1])+costs[i-1][2];
            }
            //返回 最后一次粉刷 三种颜色 其中的最小花费
            return min(min(dp[n][0],dp[n][1]),dp[n][2]);
    }
};

Initialization
Using the state transition equation, when i is 0, an out-of-bounds access will occur, so expand a row
when i is 0, that is, after the painting of No. 0 house is red/blue/green, the minimum cost at this time
is due to No. 0 house It is the very beginning, so the minimum cost is the element corresponding to the costs array.
Just set all rows of the expanded column to 0.

When the last house is painted, it is counted as an expense record,
so the minimum cost of comparing the last three colors of red/blue/green is the minimum cost

309. The best time to buy and sell stocks includes a freezing period

Click to view: The best time to buy and sell stocks includes a freezing period


Given an integer array prices, where prices[i] represents the stock price on the i-th day. ​Design
an algorithm to calculate the maximum profit. Under the following constraints, you can complete as many transactions as possible (buy and sell a stock multiple times):
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).

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

topic analysis

If you buy a stock and sell it, you will enter the freezing period, and you can’t do anything.
Finally, the maximum profit above is 3

state transition equation

dp[i]: Indicates the maximum profit that can be obtained at the end of the i-th day.
There are four states at position i: Hold stocks and keep selling stocks. Selling stocks during the freezing period
will denote the state of holding stocks with subscript 0 , the subscript 1 will be used to indicate the status of selling stocks, the subscript 2 will be used to indicate the status of selling stocks, and the subscript 3 will be used to indicate the freezing period, that is,
dp[i][0] holding stocks dp[i][1] Keep selling stock dp[i][2] selling stock dp[i][3] freezing period

dp[i][0]: Indicates that after the end of the i-th day, it is in the state of holding stocks, and the maximum profit at this time
dp[i][1]: Indicates that after the end of the i-th day, it is in a state of keeping selling stocks. At this time The maximum profit
dp[i][2]: indicates that after the end of the i-th day, it is in the state of selling stocks, and the maximum profit at this time
dp[i][3]: indicates that after the end of the i-th day, it is in the state of freezing period. maximum profit when

Sell ​​the stock before the freezing period, and keep selling the stock after the freezing period if you do nothing

hold stock

If the i-1 day is in the state of holding stocks, the i-th day continues the state of the i-1 day.
In this case: dp[i][0]=dp[i-1][0]


If the i-1th day is the freezing period, the i-th day is the state of buying stocks
From the i-1th day to the i-th day, the stock price needs to be subtracted
In this case: dp[i][0]=dp[i -1][3]-price[i]


From the end of the freezing period until the i-1th day, the state of selling stocks is maintained, and the i-th day is in the state of buying stocks.
In this case: dp[i][0]=dp[i-1][1] -price[i]


The state transition equation for taking the maximum value of the three
is:
dp[i][0]= max ( max(dp[i-1][0],dp[i-1][3]-price[i]) ,dp [i-1][1]-price[i]);

keep selling stocks

If you want to keep selling stocks on day i, then you can keep selling stocks on day i-1.
In this case: dp[i][1]= dp[i-1][1]


If you want to sell stocks on the i-th day, then the i-1th day can be in the frozen state.
In this case: dp[i][1]=dp[i-1][3]


Take the maximum value of the two
state transition equations:
dp[i][1]=max(dp[i-1][1],dp[i-1][3]);

sell stock

Hold stocks on day i-1, sell stocks on day i
From day i-1 to day i, you need to add the stock price

The state transition equation is:
dp[i][2]= dp[i-1][0]+price[i];

freezing period

The state of selling stocks on day i-1, the state of freezing period on day i

The state transition equation is:
dp[i][3] = dp[i-1][2];

full code

class Solution {
    
    
public:
    int maxProfit(vector<int>& prices) {
    
    
     int n=prices.size();
     int i=0;
     vector<vector<int>>dp(n,vector<int>(4,0));
     //将股票买了,需要花钱 所以利润为负
     dp[0][0]=-prices[0];
     for(i=1;i<n;i++)
     {
    
    
         //持有股票
         dp[i][0]= max( max(dp[i-1][0],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];
     }
     //最后一天 若买入 则不会获得最大利润 ,所以去除下标为0的情况
     return max(max(dp[n-1][1],dp[n-1][2]),dp[n-1][3]);
    }
};

714. The best time to buy and sell stocks includes handling fees

Click to view: The best time to buy and sell stocks includes handling fees


Given an integer array prices, where prices[i] represents the stock price on the i-th day; 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 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.

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 sell prices[3] = 8
buy here prices[4] = 4
sell here prices[5] = 9
total profit: ((8 - 1) - 2) + ((9 - 4) - 2 ) = 8

topic analysis

When the value of the array element is 1, it is uneconomical to buy stocks when the value of the array element is 3 or 2. When the value of the array element is 8
, Sell ​​stocks, 8-1-2=5
When the array element value is 4, buy stocks, when the array element value is 9, sell stocks, 9-4-2=3
The maximum profit is: 5+3= 8

state transition equation

dp[i]: indicates the maximum profit that can be obtained after the end of the i-th day


At position i, there are two states, buy state and sell state

f[i]: indicates that after the end of the i-th day, it is in the state of buying, and the maximum profit at this time
g[i]: indicates that after the end of the i-th day, it is in the state of selling, and the maximum profit at this time


You only need to pay the handling fee once, assuming that the handling fee is added when selling the stock

f[i] state transition equation

If the i-1 day is in the buying state, and the i-th day does nothing, then the i-th day is also in the buying state.
In this case: f[i]=f[i-1]


If the i-1 day is in the selling state, then the i-th day is in the buying state.
It is necessary to subtract the price[i] corresponding to the purchase of the stock.
In this case: f[i]=g[i-1]-price[i ]

The state transition equation is:
f[i] =max(f[i-1],g[i-1]-price[i]);

g[i] state transition equation

If the state is sold on the i-1 day, and nothing is done on the i day, the i-th day is also in the sell state.
In this case: g[i]=g[i-1]


If the i-1 day is in the buying state, then the i-th day is in the selling state. The
profit price[i] corresponding to selling the stock needs to be added, and at the same time, a handling fee is required for selling the stock.
In this case: g[i]=f [i-1]+price[i]-fee

The state transition equation is:
g[i]= max(g[i-1],f[i-1]+price[i]-fee);

full code

class Solution {
    
    
public:
    int maxProfit(vector<int>& prices, int fee) {
    
    
        int n=prices.size();
        int i=0;
        //f表示 买入  g表示卖出
        vector<int>f(n,0);
        vector<int>g(n,0);
        //将股票买了,需要花钱,所以利润为负
        f[0]=-prices[0];
        g[0]=0;
        for(i=1;i<n;i++)
        {
    
    
            f[i]=max(f[i-1],g[i-1]-prices[i]);
            g[i]=max(g[i-1],f[i-1]+prices[i]-fee);
        }
        //在最后一个位置处  在买股票对应的利润肯定是没有将股票卖出的利润多的
        return g[n-1];
    }
};

Guess you like

Origin blog.csdn.net/qq_62939852/article/details/131423882