|
| 1 | +// [ |
| 2 | +// [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] k = 0 |
| 3 | +// [0, 24, 24, 24, 24, 24, 35, 35, 39, 39, 40, 40] k = 1 |
| 4 | +// [0, 24, 24, 24, 24, 29, 48, 48, 61, 61, 62, 62] k = 2 |
| 5 | +// [0, 24, 24, 24, 24, 29, 48, 48, 74, 74, 75, 75] k = 3 |
| 6 | +// [0, 24, 24, 24, 24, 29, 48, 48, 74, 74, 84, 84] k = 4 |
| 7 | +// ] |
| 8 | +// 25-1; max max max max 36-1 max 40-1 max 41-1 max k = 1 |
| 9 | +// <k*2 max max 24+5 24+24 max 35+26 max 35+27 max k = 2 |
| 10 | +// <k*3 35+26 max 48+26 max 48+27 max k = 3 |
| 11 | +// <k*4 74+10 max k = 4 |
| 12 | +// prices[j] + max(prices((i - 1)*2, j) => profits[i - 1][index(p)] - p), |
| 13 | +// profits[i][j - 1], |
| 14 | +// profits[i - 1][j], |
| 15 | +// ) = max(90 - 3 + 6, 63) = 93 |
| 16 | +// where prices(i, j) = sliced i..j prices array |
| 17 | +// where index = index of min value |
| 18 | +function maxProfitWithKTransactions(prices, k) { |
| 19 | + if (!prices || prices.length < 2) return 0 |
| 20 | + if (!k || k < 1) return 0 |
| 21 | + |
| 22 | + const profits = new Array(k + 1).fill().map(() => new Array(prices.length).fill(0)) |
| 23 | + for (let i = 1; i <= k; i++) |
| 24 | + for (let j = 1; j < prices.length; j++) |
| 25 | + profits[i][j] = Math.max( |
| 26 | + prices[j] + Math.max( |
| 27 | + ...prices |
| 28 | + .slice((i - 1)*2, j) |
| 29 | + .map((p, l) => profits[i - 1][l + (i - 1)*2] - p) |
| 30 | + ), |
| 31 | + profits[i][j - 1], |
| 32 | + profits[i - 1][j], |
| 33 | + ) |
| 34 | + |
| 35 | + |
| 36 | + return profits[k][prices.length - 1] |
| 37 | +} |
| 38 | + |
| 39 | +// Do not edit the line below. |
| 40 | +exports.maxProfitWithKTransactions = maxProfitWithKTransactions; |
| 41 | + |
| 42 | +const test = true |
| 43 | +if (typeof test === 'boolean' && test) { |
| 44 | + const { expect } = require('../leetCode/utils.js'); |
| 45 | + let k |
| 46 | + expect(maxProfitWithKTransactions([]) /*?*/, 0) //?. $ |
| 47 | + expect(maxProfitWithKTransactions([5, 7]) /*?*/, 0) //?. $ |
| 48 | + k = 1 |
| 49 | + expect(maxProfitWithKTransactions([5], k) /*?*/, 0) //? |
| 50 | + expect(maxProfitWithKTransactions([5, 3], k) /*?*/, 0) //?. $ |
| 51 | + expect(maxProfitWithKTransactions([5, 11, 3, 50, 60, 90], k) /*?*/, 87) //?. $ |
| 52 | + expect(maxProfitWithKTransactions([3, 2, 5, 7, 1, 3, 7], k) /*?*/, 6) //?. $ |
| 53 | + expect(maxProfitWithKTransactions([1, 25, 24, 23, 12, 17, 36, 14, 40, 31, 41, 5], k) /*?*/, 40) //?. $ |
| 54 | + k = 2 |
| 55 | + expect(maxProfitWithKTransactions([5, 11, 3, 50, 60, 90], k) /*?*/, 93) //?. $ |
| 56 | + expect(maxProfitWithKTransactions([1, 25, 24, 23, 12, 17, 36, 14, 40, 31, 41, 5], k) /*?*/, 62) //?.s $ |
| 57 | + k = 3 |
| 58 | + expect(maxProfitWithKTransactions([5, 11, 3, 50, 60, 90], k) /*?*/, 93) //?. $ |
| 59 | + k = 4 |
| 60 | + expect(maxProfitWithKTransactions([1, 25, 24, 23, 12, 17, 36, 14, 40, 31, 41, 5], k) /*?*/, 84) //?.s $ |
| 61 | +} |
0 commit comments