-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path188.js
More file actions
29 lines (27 loc) · 846 Bytes
/
Copy path188.js
File metadata and controls
29 lines (27 loc) · 846 Bytes
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
/**
* @param {number} k
* @param {number[]} prices
* @return {number}
*/
var maxProfit = function(k, prices) {
const cache = Array.from({length: prices.length }, () => Array.from({length: 2}, () => Array.from({length: k}).fill(-1)));
function dp(idx, isHolding, k) {
if (idx === prices.length || k === 0) {
return 0;
}
if (cache[idx][isHolding][k - 1] !== -1) {
return cache[idx][isHolding][k - 1];
}
cache[idx][isHolding][k - 1] = !isHolding ?
Math.max(
dp(idx + 1, 1, k) - prices[idx],
dp(idx + 1, 0, k)
) :
Math.max(
dp(idx + 1, 0, k - 1) + prices[idx],
dp(idx + 1, 1, k)
);
return cache[idx][isHolding][k - 1];
}
return dp(0, 0, k);
};