Untitled

 avatar
unknown
plain_text
a month ago
1.6 kB
3
Indexable
import java.util.Arrays;

public class BestBasketballTeam {
    public int bestTeamScore(int[] scores, int[] ages) {
        int n = scores.length;
        int[][] players = new int[n][2];

        // Step 1: Pair up (age, score) and sort
        for (int i = 0; i < n; i++) {
            players[i][0] = ages[i];   // Age
            players[i][1] = scores[i]; // Score
        }

        // Sort by age first, then by score (ensures no younger player has a higher score)
        Arrays.sort(players, (a, b) -> (a[0] == b[0]) ? a[1] - b[1] : a[0] - b[0]);

        // Step 2: DP to find the maximum valid team score
        int[] dp = new int[n];
        int maxScore = 0;

        for (int i = 0; i < n; i++) {
            dp[i] = players[i][1]; // Base case: team with just this player

            for (int j = 0; j < i; j++) {
                if (players[j][1] <= players[i][1]) { // No conflict
                    dp[i] = Math.max(dp[i], dp[j] + players[i][1]);
                }
            }

            maxScore = Math.max(maxScore, dp[i]); // Track max team score
        }

        return maxScore;
    }

    public static void main(String[] args) {
        BestBasketballTeam solver = new BestBasketballTeam();
        System.out.println(solver.bestTeamScore(new int[]{1, 3, 5, 10, 15}, new int[]{1, 2, 3, 4, 5})); // 34
        System.out.println(solver.bestTeamScore(new int[]{4, 5, 6, 5}, new int[]{2, 1, 2, 1})); // 16
        System.out.println(solver.bestTeamScore(new int[]{1, 2, 3, 5}, new int[]{8, 9, 10, 1})); // 6
    }
}
Editor is loading...
Leave a Comment