k-layer machine
Time O(n × k) Space O(k)For each price, for j = 1..k: buy[j] = max(buy[j], sell[j − 1] − p); sell[j] = max(sell[j], buy[j] + p).
import java.util.Arrays;
class Solution {
public int maxProfit(int k, int[] prices) {
int n = prices.length;
if (k >= n / 2) {
int profit = 0;
for (int i = 1; i < n; i++) profit += Math.max(0, prices[i] - prices[i - 1]);
return profit;
}
int[] buy = new int[k + 1], sell = new int[k + 1];
Arrays.fill(buy, Integer.MIN_VALUE / 2);
for (int p : prices)
for (int j = 1; j <= k; j++) {
buy[j] = Math.max(buy[j], sell[j - 1] - p);
sell[j] = Math.max(sell[j], buy[j] + p);
}
return sell[k];
}
}Verdict: Generalises the one- and two-transaction versions.