LeetCode 题解工作台
无矛盾的最佳球队
假设你是球队的经理。对于即将到来的锦标赛,你想组合一支总体得分最高的球队。球队的得分是球队中所有球员的分数 总和 。 然而,球队中的矛盾会限制球员的发挥,所以必须选出一支 没有矛盾 的球队。如果一名年龄较小球员的分数 严格大于 一名年龄较大的球员,则存在矛盾。同龄球员之间不会发生矛盾。 给你两个列表…
3
题型
6
代码语言
3
相关题
当前训练重点
中等 · 状态·转移·动态规划
答案摘要
我们可以将球员按照分数从小到大排序,如果分数相同,则按照年龄从小到大排序。 接下来,使用动态规划求解。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 状态·转移·动态规划 题型思路
题目描述
假设你是球队的经理。对于即将到来的锦标赛,你想组合一支总体得分最高的球队。球队的得分是球队中所有球员的分数 总和 。
然而,球队中的矛盾会限制球员的发挥,所以必须选出一支 没有矛盾 的球队。如果一名年龄较小球员的分数 严格大于 一名年龄较大的球员,则存在矛盾。同龄球员之间不会发生矛盾。
给你两个列表 scores 和 ages,其中每组 scores[i] 和 ages[i] 表示第 i 名球员的分数和年龄。请你返回 所有可能的无矛盾球队中得分最高那支的分数 。
示例 1:
输入:scores = [1,3,5,10,15], ages = [1,2,3,4,5] 输出:34 解释:你可以选中所有球员。
示例 2:
输入:scores = [4,5,6,5], ages = [2,1,2,1] 输出:16 解释:最佳的选择是后 3 名球员。注意,你可以选中多个同龄球员。
示例 3:
输入:scores = [1,2,3,5], ages = [8,9,10,1] 输出:6 解释:最佳的选择是前 3 名球员。
提示:
1 <= scores.length, ages.length <= 1000scores.length == ages.length1 <= scores[i] <= 1061 <= ages[i] <= 1000
解题思路
方法一:排序 + 动态规划
我们可以将球员按照分数从小到大排序,如果分数相同,则按照年龄从小到大排序。
接下来,使用动态规划求解。
我们定义 表示以排序后的第 个球员作为最后一个球员的最大得分,那么答案就是 。
对于 ,我们可以枚举 ,如果第 个球员的年龄大于等于第 个球员的年龄,则 可以从 转移而来,转移方程为 。然后我们将第 个球员的分数加到 中,即 。
最后,我们返回 即可。
时间复杂度 ,空间复杂度 。其中 为球员的数量。
class Solution:
def bestTeamScore(self, scores: List[int], ages: List[int]) -> int:
arr = sorted(zip(scores, ages))
n = len(arr)
f = [0] * n
for i, (score, age) in enumerate(arr):
for j in range(i):
if age >= arr[j][1]:
f[i] = max(f[i], f[j])
f[i] += score
return max(f)
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Assess if the candidate recognizes the need to sort players to avoid conflicts.
- question_mark
Check if the candidate can explain dynamic programming in the context of maximizing the score.
- question_mark
Evaluate how the candidate handles edge cases, such as when all players are of the same age or score.
常见陷阱
外企场景- error
Forgetting to sort the players correctly, which could lead to conflicts and incorrect results.
- error
Using a greedy approach instead of dynamic programming, missing the optimal team combination.
- error
Not considering edge cases like players of the same age or when no valid team can be formed.
进阶变体
外企场景- arrow_right_alt
Consider additional constraints where the number of players is limited or when there is an upper bound on the team size.
- arrow_right_alt
Change the problem to allow conflicts if the difference in scores is small.
- arrow_right_alt
Introduce other constraints, such as a fixed number of players that must be selected.