Best Team With No Conflicts Problem
Description
LeetCode Problem 1626.
You are the manager of a basketball team. For the upcoming tournament, you want to choose the team with the highest overall score. The score of the team is the sum of scores of all the players in the team.
However, the basketball team is not allowed to have conflicts. A conflict exists if a younger player has a strictly higher score than an older player. A conflict does not occur between players of the same age.
Given two lists, scores and ages, where each scores[i] and ages[i] represents the score and age of the i^th player, respectively, return the highest overall score of all possible basketball teams.
Example 1:
Input: scores = [1,3,5,10,15], ages = [1,2,3,4,5]
Output: 34
Explanation: You can choose all the players.
Example 2:
Input: scores = [4,5,6,5], ages = [2,1,2,1]
Output: 16
Explanation: It is best to choose the last 3 players. Notice that you are allowed to choose multiple people of the same age.
Example 3:
Input: scores = [1,2,3,5], ages = [8,9,10,1]
Output: 6
Explanation: It is best to choose the first 3 players.
Constraints:
1 <= scores.length, ages.length <= 1000scores.length == ages.length1 <= scores[i] <= 10^61 <= ages[i] <= 1000
Solution
Approach: Sort, Then Longest-Increasing-Subsequence Style DP
A team has a conflict when a younger player scores strictly more than an older one. Sort the players by score, breaking ties by age. Now walk through a team in this order: scores never decrease, so the team has no conflict exactly when the ages never decrease either.
Two details make that exact:
- Players with equal scores never conflict, and sorting them by age keeps their ages non-decreasing, so they can always be taken together.
- Players with equal ages never conflict, which is why the age condition is "never decreases" (
<=), not "increases".
So the problem becomes: choose a subsequence of the sorted players with non-decreasing ages and maximum total score. Let best[i] be the highest score of such a team whose last player is player i:
best[i] = score[i] + max(best[j]) over j < i with age[j] <= age[i] (or just score[i] if there is none).
The answer is the largest best[i]. The total is at most 1000 · 106 = 109, which fits in a 32-bit integer.
Complexity: O(n2) time for the DP after an O(n log n) sort, and O(n) extra space.
class Solution:
def bestTeamScore(self, scores: List[int], ages: List[int]) -> int:
# Sort by score (then age): a team is then valid exactly when its ages never decrease.
players = sorted(zip(scores, ages))
n = len(players)
best = [0] * n # best[i] = highest team score whose last player is players[i]
for i, (score, age) in enumerate(players):
for j in range(i):
if players[j][1] <= age:
best[i] = max(best[i], best[j])
best[i] += score
return max(best)