leetcode123 - Best Time to Buy and Sell Stock III - hard

Say you have an array for which the ith element is the price of a given stock on day i.
Design an algorithm to find the maximum profit. You may complete at most two transactions.
Note: You may not engage in multiple transactions at the same time (i.e., you must sell the stock before you buy again).
Example 1:
Input: [3,3,5,0,0,3,1,4]
Output: 6
Explanation: Buy on day 4 (price = 0) and sell on day 6 (price = 3), profit = 3-0 = 3.
Then buy on day 7 (price = 1) and sell on day 8 (price = 4), profit = 4-1 = 3.
Example 2:
Input: [1,2,3,4,5]
Output: 4
Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4.
Note that you cannot buy on day 1, buy on day 2 and sell them later, as you are
engaging multiple transactions at the same time. You must sell before buying again.

 

DP。O(n^3)。可延伸到k次交易。
定义: dp[i][j] 为最多允许交易i次,从0~j天,你可能获得的最大利润。
初始化:第一行都为0(不允许交易),第一列都为0(只有一天不能卖)
递推公式:dp[i][j] = max(dp[i][j - 1], prices[j] - prices[m] + T[I - 1][m]),对所有在[0, j]的m。
解释:每一步,要么不卖股票(dp[i][j - 1]。 要么卖股票,而且这次卖的股票是从第m天买的,那么m天它的操作维度要让操作次数下降一级)。因为允许交易次数是从0开始不断向上刷新到k的,所以正确性有所保证。

 

细节:
1.一个错误的解题逻辑:靠选出最大的两段上升区间,加起来返回结果。例如[1,2,4,2,5,7,2,4,9,0]应该是13而不是12.
2.注意prices下标的offset。

 

实现:

class Solution {
    public int maxProfit(int[] prices) {
         // P1: 靠选出最大的两段上升区间,加起来返回结果的逻辑是错的。例如[1,2,4,2,5,7,2,4,9,0]应该是13而不是12.
        
        if (prices == null || prices.length == 0) {
            return 0;
        }
        
        int[][] dp = new int[2 + 1][prices.length + 1];
        
        for (int j = 0; j < dp[0].length; j++) {
            dp[0][j] = 0;
        }
        
        for (int i = 0; i < dp.length; i++) {
            dp[i][0] = 0;
        }
        
        for (int i = 1; i < dp.length; i++) {
            for (int j = 1; j < dp[0].length; j++) {
                dp[i][j] = Math.max(dp[i][j], dp[i][j - 1]);
                for (int m = 1; m <= j; m++) {
                    // P2: 注意prices下标的offset。
                    dp[i][j] = Math.max(dp[i][j], prices[j - 1] - prices[m - 1] + dp[i - 1][m]);
                }
            }
        }
        
        return dp[dp.length - 1][dp[0].length - 1];
    }
}

 

posted @ 2018-09-25 03:17  jasminemzy  阅读(130)  评论(0编辑  收藏  举报