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
Solution: Sort + DP
Sort by (age, score) in descending order. For j < i, age[j] >= age[i]
dp[i] = max(dp[j] | score[j] >= score[i], j < i) + score[i]
Basically, we want to find the player j with best score among [0, i), and make sure score[i] <= score[j] (since age[j] >= age[i]) then we won’t have any conflicts.
ans = max(dp)
C++
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
// Author: Huahua class Solution { public: int bestTeamScore(vector<int>& scores, vector<int>& ages) { const int n = scores.size(); vector<pair<int, int>> players(n); for (int i = 0; i < n; ++i) players[i] = {ages[i], scores[i]}; sort(rbegin(players), rend(players)); // dp[i] = max score of the first i players, i must be selected. vector<int> dp(n); for (int i = 0; i < n; ++i) { for (int j = 0; j < i; ++j) if (players[i].second <= players[j].second) dp[i] = max(dp[i], dp[j]); dp[i] += players[i].second; } return *max_element(begin(dp), end(dp)); } }; |
请尊重作者的劳动成果,转载请注明出处!花花保留对文章/视频的所有权利。
如果您喜欢这篇文章/视频,欢迎您捐赠花花。
If you like my articles / videos, donations are welcome.
Be First to Comment