这题没做出来。需要复习
- stock III可以划归为两个stock I问题,每个的Space是O(n), 不过真的太难想到了。。
Comparing to I and II, III limits the number of transactions to 2. This can be solve by "devide and conquer". We use left[i] to track the maximum profit for transactions before i, and use right[i] to track the maximum profit for transactions after i. You can use the following example to understand the Java solution:
Prices: 1 4 5 7 6 3 2 9
left = [0, 3, 4, 6, 6, 6, 6, 8]
right= [8, 7, 7, 7, 7, 7, 7, 0]
The maximum profit = 13
public class Solution {
public int maxProfit(int[] prices) {
//solution1:
if(prices.length == 0) return 0;
int length = prices.length;
int[] left = new int[length];
int[] right = new int[length];
// DP from left to right
left[0] = 0;
int min = prices[0];
for (int i = 1; i < prices.length; i++) {
min = Math.min(min, prices[i]);
left[i] = Math.max(left[i - 1], prices[i] - min);
}
// DP from right to left
right[prices.length - 1] = 0;
int max = prices[prices.length - 1];
for (int i = prices.length - 2; i >= 0; i--) {
max = Math.max(max, prices[i]);
right[i] = Math.max(right[i + 1], max - prices[i]);
}
int profit = 0;
for (int i = 0; i < prices.length; i++) {
profit = Math.max(profit, left[i] + right[i]);
}
return profit;
}
}
-
扩展问题, 若有K个transaction怎么做?
(1)肯定是二维DP, 但二维不代表复杂度为O(n^2).这里是O(kn)
(2)思考一: K和n在DP过程中分别代表什么?
K代表at most K个transaction的状态, n代表DP进行到price[n]的状态*
(3)思考二: 递推公式是什么?
从关键字"At most"出发: