Sponsored
Sponsored
First, pair up each player's score and age, and then sort them based on age and score. This allows us to always build teams that do not violate the conflict rule of younger players having higher scores than older players. Subsequently, use dynamic programming to build the optimal solution progressively by calculating the best team score achievable up to this player, considering current player's score only if it resolves no conflicts by adhering to the sorted order.
Time Complexity: O(n^2), where n is the number of players.
Space Complexity: O(n) for the DP array.
1#include <vector>
2#include <algorithm>
3using namespace std;
4
5class Solution {
6public:
7 int bestTeamScore(vector<int>& scores, vector<int>& ages) {
8 int n = scores.size();
9 vector<pair<int, int>> players;
10 for (int i = 0; i < n; ++i) {
11 players.push_back({ages[i], scores[i]});
12 }
13 sort(players.begin(), players.end());
14
15 vector<int> dp(n);
16 int maxScore = 0;
17 for (int i = 0; i < n; ++i) {
18 dp[i] = players[i].second;
19 for (int j = 0; j < i; ++j) {
20 if (players[j].second <= players[i].second) {
21 dp[i] = max(dp[i], dp[j] + players[i].second);
22 }
23 }
24 maxScore = max(maxScore, dp[i]);
25 }
26 return maxScore;
27 }
28};
The C++ implementation involves creating a vector of pairs and sorting it. It then uses DP to calculate the largest possible team score by considering each combination without conflicts.