LeetCode 123. Best Time to Buy and Sell Stock III

Question

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
2
3
4
5
6
7
8
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.


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.

Solution

  • state: dp[ t + 1 ] [ days ] 表示进行t次交易后最大能获得的收益。

  • init: 均为0。

  • func:

    1
    2
    3
    4
    for (int k = 0; k < j; k++) {
    max = Math.max(max, prices[j] - prices[k] + dp[i - 1][k]); // 看第k天买入,j天卖出。并且需要加上上次交易k天剩下的钱
    }
    dp[i][j] = Math.max(max, dp[i][j - 1]);
  • res: dp[ t ] [ days - 1]

通过上面的观察发现,我们需要追踪选择哪个k的情况下,我们可以获得最大的利益,具体可以看下面的代码。

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
// time:O(kNM) space:O(m*n)
public int maxProfit(int[] prices) {
if (prices == null || prices.length == 0) return 0;
int t = 2;
int days = prices.length;
int[][] dp = new int[t + 1][days];
for (int i = 1; i < t + 1; i++) {
for (int j = 1; j < days; j++) {
int max = 0;
for (int k = 0; k < j; k++) {
max = Math.max(max, prices[j] - prices[k] + dp[i - 1][k]);
}
dp[i][j] = Math.max(max, dp[i][j - 1]);
}
}
return dp[t][days - 1];
}

// O(M*N) space:O(M*N)
public int maxProfit2(int[] prices) {
if (prices == null || prices.length == 0) return 0;
int m = 2;
int n = prices.length;
int[][] dp = new int[m + 1][n];
for (int i = 1; i <= m; i++) {
int maxDiff = -prices[0];
for (int j = 1; j < n; j++) {
dp[i][j] = Math.max(dp[i][j - 1], prices[j] + maxDiff);
maxDiff = Math.max(maxDiff, dp[i - 1][j] - prices[j]);
}
}
return dp[m][n - 1];
}

Reference