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 34 35 36 37 38 39 40
| const maxProfit = function(k, prices) { let n = prices.length const maxProfit2 = function(prices) { let profit_out = 0 let profit_in = -prices[0] for (let i = 1; i < n; i++) { profit_out = Math.max(profit_out, profit_in + prices[i]) profit_in = Math.max(profit_in, profit_out - prices[i]) } return profit_out }
if (k > n / 2) { return maxProfit2(prices) }
let profit = new Array(k) for (let j = 0; j <= k; j++) { profit[j] = { profit_in: -prices[0], profit_out: 0 } } for (let i = 1; i < n; i++) { for (let j = 1; j <= k; j++) { profit[j] = {
profit_out: Math.max(profit[j].profit_out, profit[j].profit_in + prices[i]), profit_in: Math.max(profit[j].profit_in, profit[j-1].profit_out - prices[i]) } } } return profit[k].profit_out }
|