Skip to content

1626. Best Team With No Conflicts 👍

  • Time: $O(n^2)$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
struct Player {
  int age;
  int score;
  Player(int age, int score) : age(age), score(score) {}
};

class Solution {
 public:
  int bestTeamScore(vector<int>& scores, vector<int>& ages) {
    const int n = scores.size();
    vector<Player> players;
    // dp[i] := the maximum score of choosing the players[0..i] with the
    // players[i] being selected
    vector<int> dp(n);

    for (int i = 0; i < n; ++i)
      players.emplace_back(ages[i], scores[i]);

    ranges::sort(players, [](const Player& a, const Player& b) {
      return a.age == b.age ? a.score > b.score : a.age > b.age;
    });

    for (int i = 0; i < n; ++i) {
      // For each player, choose it first.
      dp[i] = players[i].score;
      // players[j].age >= players[i].age since we sort in descending order.
      // So, we only have to check that players[j].score >= players[i].score.
      for (int j = 0; j < i; ++j)
        if (players[j].score >= players[i].score)
          dp[i] = max(dp[i], dp[j] + players[i].score);
    }

    return ranges::max(dp);
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
class Solution {
  public int bestTeamScore(int[] scores, int[] ages) {
    record Player(int age, int score) {}
    final int n = scores.length;
    Player[] players = new Player[n];
    // dp[i] := the maximum score of choosing the players[0..i] with the players[i] being selected
    int[] dp = new int[n];

    for (int i = 0; i < n; ++i)
      players[i] = new Player(ages[i], scores[i]);

    Arrays.sort(players,
                (a, b) //
                -> a.age == b.age ? Integer.compare(b.score, a.score)
                                  : Integer.compare(b.age, a.age));

    for (int i = 0; i < n; ++i) {
      // For each player, choose it first.
      dp[i] = players[i].score;
      // players[j].age >= players[i].age since we sort in descending order.
      // So, we only have to check that players[j].score >= players[i].score.
      for (int j = 0; j < i; ++j)
        if (players[j].score >= players[i].score)
          dp[i] = Math.max(dp[i], dp[j] + players[i].score);
    }

    return Arrays.stream(dp).max().getAsInt();
  }
}