Leekow-123 The best time to buy and sell stocks III (dp)

Leetour-123 The best time to buy and sell stocks III

1. Topic

123. Best Time to Buy and Sell Stocks III

Given an array whose i i-th element is the price of a given stock on iday .

Design an algorithm to calculate the maximum profit you can make. You can complete up to two transactions.

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

Example 1:

输入:prices = [3,3,5,0,0,3,1,4]
输出:6
解释:在第 4 天(股票价格 = 0)的时候买入,在第 6 天(股票价格 = 3)的时候卖出,这笔交易所能获得利润 = 3-0 = 3 。
     随后,在第 7 天(股票价格 = 1)的时候买入,在第 8 天 (股票价格 = 4)的时候卖出,这笔交易所能获得利润 = 4-1 = 3 。

2. Analysis

  1. topic. The difference between this question and 122 The best time to buy and sell stocks II is that the number of transactions is limited to 2 . This kind of dp question is the division of states. It is more convenient and appropriate to see how to divide. The previous question is obviously two states, so of course this can be thought of as four states:

    1. The first and second ownership (buy) status (the status of stocks that exist for many days)

    • Did not own it last time, bought it this time
    • Previously owned, no operation this time

    2. The first and second unowned (sold) status

    • Not owned the previous day, no operation this time
    • Owned the day before, sold this time
  2. Set up the dp array, according to the above analysis, we have 4 states in total, so we set up a two-dimensional array, dp[i][5], 1-4 correspond to the first transaction and the second transaction respectively. The reason why the length is set to 5 here is that when the first purchase of state 1 is made later, there is no need to set the initial value starting from 0, because the default array value is 0.

  3. traverse. The previous dp is also needed, so we traverse from front to back .

3. Code and comments

class Solution {
    
    
    public int maxProfit(int[] prices) {
    
    
        // 1.4个状态,1第一次买入,2第一次卖出,3第二次买入,4第二次卖出
        int n = prices.length;
        int[][] dp = new int[n][5];
		
        // 2.第一二次的买入
        dp[0][1] = -prices[0];
        dp[0][3] = -prices[0];

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

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

4. Practice

Link to the topic : 123. The best time to buy and sell stocks III

Guess you like

Origin blog.csdn.net/qq_51326491/article/details/129344090