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.
1public class Solution {
2 public int BestTeamScore(int[] scores, int[] ages) {
3 var players = new List<(int age, int score)>();
4 for (int i = 0; i < scores.Length; i++) {
5 players.Add((ages[i], scores[i]));
6 }
7 players = players.OrderBy(p => p.age).ThenBy(p => p.score).ToList();
8
9 var dp = new int[scores.Length];
10 int maxScore = 0;
11
12 for (int i = 0; i < scores.Length; i++) {
13 dp[i] = players[i].score;
14 for (int j = 0; j < i; j++) {
15 if (players[j].score <= players[i].score) {
16 dp[i] = Math.Max(dp[i], dp[j] + players[i].score);
17 }
18 }
19 maxScore = Math.Max(maxScore, dp[i]);
20 }
21
22 return maxScore;
23 }
24}
C# solution mirrors the previously described approach using LINQ to sort players and apply dynamic programming to find the maximum team score without conflicts.