【LeetCode】123. 买卖股票的最佳时机 III

一、题目

给定一个数组,它的第 i 个元素是一支给定的股票在第 i 天的价格。

设计一个算法来计算你所能获取的最大利润。你最多可以完成 两笔 交易。

注意: 你不能同时参与多笔交易(你必须在再次购买前出售掉之前的股票)。

示例 1:

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

示例 2:

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

示例 3:

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

二、 解决

系列:【LeetCode】121. 买卖股票的最佳时机【LeetCode】122. 买卖股票的最佳时机 II

1、递归

思路:

买卖两次状态转换举例:

  • 不动/买入 --> 不动/卖出;
  • 不动/卖出 -->不动/买入
    买卖

以数组[1,2,3,4,5]为例,其递归调用树如下:
例子

代码:

// 参数含义: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);
    }
}

时间复杂度: O ( 2 n ) O(2^n) O(2n)
空间复杂度: O ( l o g n ) O(logn) O(logn)

2、递归+记忆化

思路:

这里需要把重复调用的结果缓存下来。另外为了将(day - 哪天; status - 买/卖; k - 交易次数)对应的结果缓存下来,还需要实现hashCode()与equals()。这个也需要好好理解一下。
过程

代码:

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);
    }
}

时间复杂度: O ( k n ) O(kn) O(kn) ?
空间复杂度: O ( k n ) O(kn) O(kn) ?

3、动态规划

思路:

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]    // 买
                  }

代码:

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];
    }
}

时间复杂度: O ( k n ) O(kn) O(kn),k = 3
空间复杂度: O ( k n ) O(kn) O(kn)

版本2

思路:

同上,但是对dp进行压缩,因为dp[i]的值主要依赖于dp[i-1]。

代码:

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];
    }
}

时间复杂度: O ( k n ) O(kn) O(kn),k=3
空间复杂度: O ( k ) O(k) O(k)

版本3

思路:

同上,可读性提升,但是通用性下降。

代码:

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;
    }
}

时间复杂度: O ( n ) O(n) O(n)
空间复杂度: O ( 1 ) O(1) O(1)

三、参考

1、五种实现+详细图解 123.买卖股票的最佳时机 III
2、Detail explanation of DP solution

猜你喜欢

转载自blog.csdn.net/HeavenDan/article/details/108982641