Skip to content

Commit 4dc7c3b

Browse files
authored
Update 2218-maximum-value-of-k-coins-from-piles.js
1 parent d6a84aa commit 4dc7c3b

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

2218-maximum-value-of-k-coins-from-piles.js

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,3 +19,29 @@ var maxValueOfCoins = function(piles, k) {
1919
}
2020
return dp[k];
2121
};
22+
23+
// another
24+
25+
/**
26+
* @param {number[][]} piles
27+
* @param {number} k
28+
* @return {number}
29+
*/
30+
const maxValueOfCoins = function(piles, k) {
31+
const n = piles.length
32+
const memo = Array.from({ length: n + 1 }, () => Array(k + 1).fill(null))
33+
return helper(0, k)
34+
35+
function helper(i, k) {
36+
if(k == 0 || i === n) return 0
37+
if(memo[i][k] != null) return memo[i][k]
38+
let res = helper(i + 1, k)
39+
let cur = 0
40+
41+
for(let j = 0; j < Math.min(piles[i].length, k); j++) {
42+
cur += piles[i][j]
43+
res = Math.max(res, cur + helper(i + 1, k - j - 1))
44+
}
45+
return memo[i][k] = res
46+
}
47+
};

0 commit comments

Comments
 (0)