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

Given an integer array, the i-th element 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 (buying and selling a stock multiple times):
You cannot participate in multiple transactions at the same time (you must sell the previous stock before buying again).
After you sell the stock, you cannot buy the stock the next day (ie, the freezing period is 1 day).
Example:
Input: [1,2,3,0,2]
Output: 3
Explanation: The corresponding transaction status is: [Buy, Sell, Freeze Period, Buy, Sell]

class Solution {
    
    
    public int maxProfit(int[] prices) {
    
    
        if(prices.length==0||prices==null){
    
    
            return 0;
        }
        int pr_0=0;
        int pr_1=Integer.MIN_VALUE;
        int pr_2_0=0;
        for(int i=0;i<prices.length;i++){
    
    
            int temp = pr_0;
            pr_0=Math.max(pr_0,pr_1+prices[i]);
            pr_1=Math.max(pr_1,pr_2_0-prices[i]);
            pr_2_0=temp;
        }

        return pr_0;
    }
}

Guess you like

Origin blog.csdn.net/sakura_wmh/article/details/111601549