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.
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 <= 1000
scores.length == ages.length
1 <= scores[i] <= 106
1 <= ages[i] <= 1000
无矛盾的最佳球队。
假设你是球队的经理。对于即将到来的锦标赛,你想组合一支总体得分最高的球队。球队的得分是球队中所有球员的分数 总和 。
然而,球队中的矛盾会限制球员的发挥,所以必须选出一支 没有矛盾 的球队。如果一名年龄较小球员的分数 严格大于 一名年龄较大的球员,则存在矛盾。同龄球员之间不会发生矛盾。
给你两个列表 scores 和 ages,其中每组 scores[i] 和 ages[i] 表示第 i 名球员的分数和年龄。请你返回 所有可能的无矛盾球队中得分最高那支的分数 。
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/best-team-with-no-conflicts
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路是DP,而且这道题是类似300题那一类的DP。
首先我们需要把题目给的两个长度为 n 的一维数组转化成一个长度为 n 的二维数组。之后我们对这个二维数组排序,年龄一样,得分小的在前;否则年龄小的在前。因为题目中定义的矛盾是在分数相同的情况下,年龄小的人会和年龄大的人存在矛盾。我们这样排序之后,是不会遇到两个得分相同但是年龄不同的人需要我们去做取舍的。
排序之后我们定义一个长度为 n 的DP数组,定义是以第 i 名球员为结尾的一票人的得分是多少。这里就类似 LIS 的思想了,具体见代码。
时间O(n^2)
空间O(n)
Java实现
1 class Solution { 2 public int bestTeamScore(int[] scores, int[] ages) { 3 // corner case 4 if (scores == null || scores.length <= 1) { 5 return scores[0]; 6 } 7 8 // normal case 9 int n = scores.length; 10 int[][] people = new int[n][2]; 11 for (int i = 0; i < n; i++) { 12 people[i][0] = ages[i]; 13 people[i][1] = scores[i]; 14 } 15 // 年龄一样,得分小的在前;否则年龄小的在前 16 Arrays.sort(people, (a, b) -> a[0] == b[0] ? a[1] - b[1] : a[0] - b[0]); 17 18 // DP定义:以 i 为结尾的一票人的得分,类似LIS 19 int[] dp = new int[n]; 20 for (int i = 0; i < n; i++) { 21 dp[i] = people[i][1]; 22 } 23 int res = 0; 24 for (int i = 0; i < n; i++) { 25 for (int j = 0; j < i; j++) { 26 if (people[j][1] <= people[i][1]) { 27 dp[i] = Math.max(dp[i], dp[j] + people[i][1]); 28 } 29 res = Math.max(res, dp[i]); 30 } 31 } 32 return res; 33 } 34 }
标签:得分,1626,No,int,scores,ages,球队,Team,team From: https://www.cnblogs.com/cnoodle/p/17078635.html