【LeetCode】 123. El mejor momento para comprar y vender acciones III

1. Título

Dada una matriz, su i-ésimo elemento es el precio de una acción dada en el i-ésimo día.

Diseña un algoritmo para calcular el máximo beneficio que puedes obtener. Puede completar hasta dos transacciones.

Nota: No puede participar en varias transacciones al mismo tiempo (debe vender las existencias anteriores antes de volver a comprar).

Ejemplo 1:

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

Ejemplo 2:

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

Ejemplo 3:

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

Dos, resolver

Serie: 【LeetCode】 121. El mejor momento para comprar y vender acciones , 【LeetCode】 122. El mejor momento para comprar y vender acciones II

1. Recurrencia

Ideas:

Ejemplos de dos transiciones de estado para compra y venta:

  • No mueva / compre -> no mueva / venda;
  • No mover / vender -> No mover / comprar
    Rebaja

Tome la matriz [1,2,3,4,5] como ejemplo, el árbol de llamadas recursivas es el siguiente:
ejemplo

Código:

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

Complejidad del tiempo: O (2 n) O (2 ^ n)O ( 2n )
Complejidad espacial: O (logn) O (logn)O ( l o g n )

2. Recursión + memorización

Ideas:

Los resultados de las llamadas repetidas deben almacenarse en caché aquí. Además, para almacenar en caché los resultados correspondientes a (día-qué día; estado-compra / venta; k-número de transacciones), es necesario implementar hashCode () y equals (). Esto también debe entenderse.
proceso

Código:

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

Complejidad de tiempo: O (kn) O (kn)O ( k n ) ?
Complejidad espacial: O (kn) O (kn)O ( k n ) ?

3. Planificación dinámica

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

Código:

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

Complejidad de tiempo: O (kn) O (kn)O ( k n ) , k = 3
Complejidad espacial: O (kn) O (kn)O ( k n )

Versión 2

Ideas:

Igual que el anterior, pero comprime dp, porque el valor de dp [i] depende principalmente de dp [i-1].

Código:

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

Complejidad de tiempo: O (kn) O (kn)O ( k n ) , k = 3
Complejidad espacial: O (k) O (k)O ( k )

Versión 3

Ideas:

Igual que antes, la legibilidad mejoró, pero la versatilidad disminuyó.

Código:

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

Complejidad de tiempo: O (n) O (n)O ( n )
complejidad espacial: O (1) O (1)O ( 1 )

Tres, referencia

1. Cinco realizaciones + ilustración detallada 123. El mejor momento para comprar y vender acciones III
2. Explicación detallada de la solución de DP

Supongo que te gusta

Origin blog.csdn.net/HeavenDan/article/details/108982641
Recomendado
Clasificación