【LeetCode】123. The best time to buy and sell stock III

1. Title

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:

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

Example 2:

输入: [1,2,3,4,5]
输出: 4
解释: 在第 1 天(股票价格 = 1)的时候买入,在第 5 天 (股票价格 = 5)的时候卖出, 这笔交易所能获得利润 = 5-1 = 4 。   
     注意你不能在第 1 天和第 2 天接连购买股票,之后再将它们卖出。   
     因为这样属于同时参与了多笔交易,你必须在再次购买前出售掉之前的股票。

Example 3:

输入: [7,6,4,3,1] 
输出: 0 
解释: 在这个情况下, 没有交易完成, 所以最大利润为 0

2. Solve

Series: 【LeetCode】121. The best time to buy and sell stocks , 【LeetCode】122. The best time to buy and sell stocks II

1. Recursion

Ideas:

Examples of two state transitions for buying and selling:

  • Do not move/buy --> do not move/sell;
  • Do not move/sell-->Do not move/buy
    Sale

Take the array [1,2,3,4,5] as an example, the recursive call tree is as follows:
example

Code:

// 参数含义:day:哪一天;  status:买入 or 卖出; k:交易次数。

class Solution {
    
    
    public int maxProfit(int[] prices) {
    
    
        if (prices==null || prices.length==0) return 0;
        int n = prices.length;
        return dfs(prices, 0, 0, 0);
    }
	
    private int dfs(int[] prices, int day, int status, int k) {
    
    
        // Terminator:数组执行到头了,或者交易了两次了
        if (day==prices.length || k==2) {
    
    
            return 0;
        }
        // Current logic:split the problem
        //定义三个变量,分别记录[不动]、[买]、[卖]
        int hold=0, buy=0, sell=0;
        
        // Drill down: conquer the subproblems 
        //保持不动
        hold = dfs(prices, day+1, status, k);
        if (status==1) {
    
    
            //递归处理卖的情况,这里需要将k+1,表示执行了一次交易
            sell = dfs(prices, day+1, 0, k+1) + prices[day];
        } else {
    
    
            //递归处理买的情况
            buy = dfs(prices, day+1, 1, k)-prices[day];
        }
        // Merge the subresults:最终结果就是三个变量中的最大值
        return Math.max(Math.max(hold, sell), buy);
    }
}

Time complexity: O (2 n) O(2^n)O ( 2n )
Space complexity: O (logn) O(logn)O ( l o g n )

2. Recursion + memoization

Ideas:

The results of repeated calls need to be cached here. In addition, in order to cache the results corresponding to (day-which day; status-buy/sell; k-number of transactions), hashCode() and equals() need to be implemented. This also needs to be understood.
process

Code:

class Key {
    
    
    final int day;
    final int status;
    final int k;
    Key(int day, int status, int k) {
    
    
        this.day = day;
        this.status = status;
        this.k = k;
    }
    // 实现自定义hashCode() 与 equals()
    public int hashCode() {
    
    
        return this.day + this.status + this.k;
    }
    public boolean equals(Object obj) {
    
    
        Key other = (Key)obj;
        if (day==other.day && status==other.status && k==other.k) {
    
    
            return true;
        }
        return false;
    }
}
    
class Solution {
    
    
    public int maxProfit(int[] prices) {
    
    
        if (prices==null || prices.length==0) return 0;
        int n = prices.length;
        // 哈希表缓存重复调用
        Map<Key, Integer> map = new HashMap<Key, Integer>();
        return dfs(map, prices, 0, 0, 0);
    }

    private int dfs(Map<Key, Integer> map, int[] prices, int day, int status, int k) {
    
    
        Key key = new Key(day, status, k);
        if (map.containsKey(key)) {
    
    
            return map.get(key);
        }
        if (day==prices.length || k==2) {
    
    
            return 0;
        }
        int hold = 0, sell = 0, buy = 0;
        hold = dfs(map, prices, day+1, status, k);
        if (status==1) {
    
    
            sell = dfs(map, prices, day+1, 0, k+1) + prices[day];
        } else {
    
    
            buy = dfs(map, prices, day+1, 1, k) - prices[day];
        }
        map.put(key, Math.max(Math.max(hold, sell), buy));
        return map.get(key);
    }
}

Time complexity: O (kn) O(kn)O ( k n ) ?
Space complexity: O (kn) O(kn)O(kn) ?

3. Dynamic planning

Ideas:

1、状态定义:
dp[cnt][i]: 第i天交易cnt次的最大利润。  cnt - 交易次数; i -2、转移方程:
dp[cnt, i] = max(dp[cnt, i-1], prices[i] - prices[j] + dp[cnt-1, j-1]), j=[0..i-1]



3、参考超哥
for day : 0-->n-1
    MP[day,0] = max {
    
     
                      MP[day-1, 0],          // 不动
                      MP[day-1, 1]+a[day]    // 卖
                    }

    MP[day,1] = max {
    
     
                      MP[day-1,1],          // 不动
                      MP[day-1,0]-a[day]    // 买
                  }

Code:

class Solution {
    
    
    public int maxProfit(int[] prices) {
    
    
        if (prices.length == 0) return 0;
        int[][] dp = new int[3][prices.length];
        for (int k = 1; k <= 2; k++) {
    
    
            int min = prices[0];
            for (int i = 1; i < prices.length; i++) {
    
    
                min = Math.min(min, prices[i] - dp[k-1][i-1]);
                dp[k][i] = Math.max(dp[k][i-1], prices[i] - min);
            }
        }

        return dp[2][prices.length-1];
    }
}

Time complexity: O (kn) O(kn)O ( k n ) , k = 3
Space complexity: O (kn) O(kn)O(kn)

Version 2

Ideas:

Same as above, but compress dp, because the value of dp[i] mainly depends on dp[i-1].

Code:

class Solution {
    
    
    public int maxProfit(int[] prices) {
    
    
        if (prices.length == 0) return 0;
        int[] dp = new int[3];
        int[] min = new int[3];
        Arrays.fill(min, prices[0]);
        for (int i = 1; i < prices.length; i++)  {
    
    
            for (int k = 1; k <= 2; k++) {
    
    
                min[k] = Math.min(min[k], prices[i] - dp[k-1]);
                dp[k] = Math.max(dp[k], prices[i] - min[k]);
            }
        }
        return dp[2];
    }
}

Time complexity: O (kn) O(kn)O ( k n ) , k=3
Space complexity: O (k) O(k)O(k)

Version 3

Ideas:

Same as above, readability improved, but versatility decreased.

Code:

class Solution {
    
    
    public int maxProfit(int[] prices) {
    
    
        int buy1 = Integer.MAX_VALUE, buy2 = Integer.MAX_VALUE;
        int sell1 = 0, sell2 = 0;

        for (int i = 0; i < prices.length; i++) {
    
    
            buy1 = Math.min(buy1, prices[i]);
            sell1 = Math.max(sell1, prices[i] - buy1);
            buy2 = Math.min(buy2, prices[i] - sell1);
            sell2 = Math.max(sell2, prices[i] - buy2);
        }
        return sell2;
    }
}

Time complexity: O (n) O(n)O ( n )
space complexity: O (1) O(1)O ( 1 )

Three, reference

1. Five realizations + detailed illustration 123. The best time to buy and sell stocks III
2. Detail explanation of DP solution

Guess you like

Origin blog.csdn.net/HeavenDan/article/details/108982641