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.
1def bestTeamScore(scores, ages):
2 players = sorted(zip(ages, scores))
3 dp = [0] * len(scores)
4 max_score = 0
5
6 for i in range(len(scores)):
7 dp[i] = players[i][1]
8 for j in range(i):
9 if players[j][1] <= players[i][1]:
10 dp[i] = max(dp[i], dp[j] + players[i][1])
11 max_score = max(max_score, dp[i])
12
13 return max_score
This solution sorts players by their ages first and scores second to ensure no conflicts. Then it uses dynamic programming to keep track of the best possible score for each player being the last player in the team.