Leetour-188 The best time to buy and sell stocks IV(dp)

Leekow-188 The best time to buy and sell stocks IV

1. Topic

188. Best Time to Buy and Sell Stocks IV

Given an array of integers prices, its i th element prices[i]is the price of a given stock on iday .

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

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

Example 1:

输入:k = 2, prices = [2,4,1]
输出:2
解释:在第 1 天 (股票价格 = 2) 的时候买入,在第 2 天 (股票价格 = 4) 的时候卖出,这笔交易所能获得利润 = 4-2 = 2 。

2. Analysis

  1. topic. The only difference between this question and 123 The best time to buy and sell stocks III is that III is up to two times, IV is up to k times, and there is an extra variable, so it is definitely necessary to add a layer of loop . According to II and III, we can also see that the state of each day is either a buying state or a selling state . So it is conceivable that we only need to write out the two states of this day each time when the k variable loops.
  2. Derive dp. From III, it is obvious that the first thing that comes to mind is a two-dimensional array, dp[i][2 * k + 1], because there are a total of k times, each with 2 states, so it is multiplied by 2.
  3. traverse. Still the same, the previous state is needed, so we traverse from front to back .

3. Code and comments

class Solution {
    
    
    public int maxProfit(int k, int[] prices) {
    
    
        int n = prices.length;
        int[][] dp = new int[n][2 * k + 1];

        // 1.初始化每次买入的初始值,区间是[1-2*k],奇数表示为买入状态,偶数表示卖出状态
        for (int i = 0; i < 2 * k; i++){
    
    
            if (i % 2 == 1){
    
    
                dp[0][i] = -prices[0];
            }
        }

        for (int i = 1; i < n; i++){
    
    
            // 2.每次两种状态
            for (int j = 1; j < 2 * k; j = j + 2){
    
    
                dp[i][j] = Math.max(dp[i - 1][j], dp[i - 1][j - 1] - prices[i]);
                dp[i][j + 1] = Math.max(dp[i - 1][j + 1], dp[i - 1][j] + prices[i]);
            }
        }
        return dp[n - 1][2 * k];
    }
}

4. Practice

Link to the topic : 188. The best time to buy and sell stocks IV

Guess you like

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