[Leetcode]1626. Best Team With No Conflicts

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 ith player, respectively, return the highest overall score of all possible basketball teams.

Logic

If we sort the input first, then we can apply dynamic programming to solve this problem with O(n^2) time complexity.

Define dp[i] as the largest score if the player[i] is selected. Therefore we have:

dp[i]=max(dp[j]+score[i]) for j in [0...i] if score[j]<=score[i]

Code

class Solution:
    def bestTeamScore(self, scores: List[int], ages: List[int]) -> int:
        players = sorted(zip(ages,scores))
        dp = [score for age,score in players]
        for i in range(1,len(players)):
            for j in range(i):
                if players[j][1] <= players[i][1]:
                    dp[i] = max(dp[i],dp[j]+players[i][1])
        return max(dp)

Reference

https://leetcode.com/problems/best-team-with-no-conflicts/

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments