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.
1import java.util.Arrays;
2
3public class Solution {
4 public int bestTeamScore(int[] scores, int[] ages) {
5 int n = scores.length;
6 int[][] players = new int[n][2];
7 for (int i = 0; i < n; i++) {
8 players[i][0] = ages[i];
9 players[i][1] = scores[i];
10 }
11 Arrays.sort(players, (a, b) -> a[0] == b[0] ? Integer.compare(a[1], b[1]) : Integer.compare(a[0], b[0]));
12
13 int[] dp = new int[n];
14 int maxScore = 0;
15 for (int i = 0; i < n; i++) {
16 dp[i] = players[i][1];
17 for (int j = 0; j < i; j++) {
18 if (players[j][1] <= players[i][1]) {
19 dp[i] = Math.max(dp[i], dp[j] + players[i][1]);
20 }
21 }
22 maxScore = Math.max(maxScore, dp[i]);
23 }
24 return maxScore;
25 }
26}
This Java solution leverages the same sorted ordering combined with a dynamic programming technique, iteratively updating maximum scores that can be achieved for each player as a team leader.