The best time to buy and sell stock III java

Given an array, its i-th element 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 two transactions.

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

Example 1:

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

Input: prices = [1,2,3,4,5]
Output: 4
Explanation: Buy on the 1st day (stock price = 1), and sell on the 5th day (stock price = 5), This exchange can make a profit = 5-1 = 4.
Note that you cannot buy stocks one after another on the first and second days and then sell them later.
Because this is involved in multiple transactions at the same time, you must sell the previous stocks before buying again.
Example 3:

Input: prices = [7,6,4,3,1]
Output: 0
Explanation: In this case, no transaction is completed, so the maximum profit is 0.
Example 4:

Input: prices = [1]
Output: 0

prompt:

1 <= prices.length <= 105
0 <= prices[i] <= 105

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

Idea: The algorithm of 3 is similar to that of 4.

class Solution {
    
    
    public int maxProfit(int[] prices) {
    
    
        int len = prices.length;
        int[][] buy = new int[len][3];//手上有股票
        int[][] sell = new int[len][3];//手上没有股票
        buy[0][0] = -prices[0];
        for (int i = 1;i <= 2;i++) {
    
    
            buy[0][i] = Integer.MIN_VALUE / 2;
            sell[0][i] = Integer.MIN_VALUE / 2;
        }
        for(int i=1;i<len;i++)
        {
    
    
            buy[i][0] = Math.max(buy[i-1][0],sell[i-1][0]-prices[i]);
            for(int j=1;j<=2;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]);
            }
        }
        int max = Integer.MIN_VALUE;
        for(int i=0;i<=2;i++)
        {
    
    
            max = Math.max(max,sell[len-1][i]);
        }
        return max;
        

    }
}

Guess you like

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