The best time to buy and sell stock IV java

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

Design an algorithm to calculate the maximum profit you can get. You can complete up to k transactions.

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

Example 1:

Input: k = 2, prices = [2,4,1]
Output: 2
Explanation: Buy on the 1st day (stock price = 2), and sell on the 2nd day (stock price = 4). Profit from this exchange = 4-2 = 2.
Example 2:

Input: k = 2, prices = [3,2,6,5,0,3]
Output: 7
Explanation: Buy on day 2 (stock price = 2), and on day 3 (stock price = 6 ) When you sell, the exchange can make a profit = 6-2 = 4.
Then, buy on the 5th day (stock price = 0) and sell on the 6th day (stock price = 3). The exchange can make a profit = 3-0 = 3.

prompt:

0 <= k <= 109
0 <= prices.length <= 1000
0 <= prices[i] <= 1000

Source: LeetCode
Link: https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-iv. The
copyright is owned by LeetCode . For commercial reprints, please contact the official authorization. For non-commercial reprints, please indicate the source.

Idea: I should have written 1, 2, 3 before. The ideas for this question are all in the notes.

class Solution {
    
    
    public int maxProfit(int k, int[] prices) {
    
    
        if (prices.length == 0) {
    
    
            return 0;
        }

        int n = prices.length;
        //最多执行n/2笔交易,买花费一天,卖花费一天
        k = Math.min(k, n / 2);
        int[][] buy = new int[n][k + 1];//手上有股票
        int[][] sell = new int[n][k + 1];//手上没股票

        buy[0][0] = -prices[0];
        sell[0][0] = 0;
        for (int i = 1; i <= k; ++i) {
    
    
            //这里取MIN_VALUE / 2,3,4,5,6都行,但是不能是MIN_VALUE
            //因为MIN_VALUE再减就变成Max_VALUE了,会导致错误
            buy[0][i] = sell[0][i] = Integer.MIN_VALUE / 4;
        }
        //System.out.println(Integer.MIN_VALUE / 2);
        //System.out.println(Integer.MIN_VALUE -5 );

        for (int i = 1; i < n; ++i) {
    
    
            //后面天数中从未有过交易的,从前一天就有股票和前一天没有股票买今天的选max
            buy[i][0] = Math.max(buy[i - 1][0], sell[i - 1][0] - prices[i]);
            for (int j = 1; j <= k; ++j) {
    
    
                buy[i][j] = Math.max(buy[i - 1][j], sell[i - 1][j] - prices[i]);
                sell[i][j] = Math.max(sell[i - 1][j], buy[i - 1][j - 1] + prices[i]);   
            }
        }
        //不一定是完成k笔交易的利润最大,比如递减序列。所以从sell【n-1】中取max
        return Arrays.stream(sell[n - 1]).max().getAsInt();
    }
}

Guess you like

Origin blog.csdn.net/weixin_43824233/article/details/111867538