[LeetCode] Best Team With No Conflicts

1626. Best Team With No Conflicts

You are the manager of a basketball team. For the upcoming tournament, you want to choose the team with the highest overall score. The score of the team is the sum of scores of all the players in the team.

However, the basketball team is not allowed to have conflicts. A conflict exists if a younger player has a strictly higher score than an older player. A conflict does not occur between players of the same age.

Given two lists, scores and ages, where each scores[i] and ages[i] represents the score and age of the ith player, respectively, return the highest overall score of all possible basketball teams.

  • Time : O(n^2)
  • Space : O(n)
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
41
class Solution {
int dp[1001];
vector<pair<int, int>> vec;
int dfs(int& n, int p) {
if(p == n) return 0;
if(dp[p] != -1) return dp[p];

int& res = dp[p] = vec[p].second;

for(int i = p + 1; i < n; i++) {
if(vec[i].first == vec[p].first) {
continue;
} else if(vec[i].second >= vec[p].second) {
res = max(res, dfs(n,i) + vec[p].second);
}
}

for(int i = p + 1; i < n and vec[p].first == vec[i].first; i++) {
res = max(res, dfs(n,i) + vec[p].second);
}

return res;
}
public:
int bestTeamScore(vector<int>& scores, vector<int>& ages) {
int n = scores.size();
memset(dp,-1,sizeof(dp));
for(int i = 0; i < n; i++) {
vec.push_back({ages[i], scores[i]});
}

sort(vec.begin(), vec.end());

int res = 0;
for(int i = 0; i < n; i++) {
res = max(res, dfs(n,i));
}

return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/02/11/PS/LeetCode/best-team-with-no-conflicts/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.