Best Team With No Conflicts LeetCode solution in JavaScript

1
var bestTeamScore = function (scores, ages) {
2
const players = scores
3
.map((score, index) => ({ score, age: ages[index] }))
4
.sort((a, b) => (a.score === b.score ? a.age - b.age : a.score - b.score));
5
let memo = new Array(scores.length).fill(0).map((_) => new Array());
6
return dfs(0, 0);
7

8
function dfs(maxAge, index) {
9
if (index === players.length) {
10
return 0;
11
}
12

13
if (memo[index][maxAge] !== undefined) {
14
return memo[index][maxAge];
15
}
16

17
let max = 0;
18
let currentPlayer = players[index];
19

20
// cannot take because I'm too young and better than an old guy in my team
21
if (currentPlayer.age < maxAge) {
22
memo[index][maxAge] = dfs(maxAge, index + 1);
23
return memo[index][maxAge];
24
}
25

26
// take
27
max = Math.max(
28
max,
29
currentPlayer.score + dfs(Math.max(maxAge, currentPlayer.age), index + 1)
30
);
31

32
// not take
33
max = Math.max(max, dfs(maxAge, index + 1));
34

35
memo[index][maxAge] = max;
36
return max;
37
}
38
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0