2491. Divide Players Into Teams of Equal Skill

Difficulty:
Related Topics:
    Similar Questions:

    Problem

    You are given a positive integer array skill of even length n where skill[i] denotes the skill of the ith player. Divide the players into n / 2 teams of size 2 such that the total skill of each team is equal.

    The chemistry of a team is equal to the product of the skills of the players on that team.

    Return **the sum of the *chemistry* of all the teams, or return -1 if there is no way to divide the players into teams such that the total skill of each team is equal.**

      Example 1:

    Input: skill = [3,2,5,1,3,4]
    Output: 22
    Explanation: 
    Divide the players into the following teams: (1, 5), (2, 4), (3, 3), where each team has a total skill of 6.
    The sum of the chemistry of all the teams is: 1 * 5 + 2 * 4 + 3 * 3 = 5 + 8 + 9 = 22.
    

    Example 2:

    Input: skill = [3,4]
    Output: 12
    Explanation: 
    The two players form a team with a total skill of 7.
    The chemistry of the team is 3 * 4 = 12.
    

    Example 3:

    Input: skill = [1,1,2,3]
    Output: -1
    Explanation: 
    There is no way to divide the players into teams such that the total skill of each team is equal.
    

      Constraints:

    Solution (Java)

    class Solution {
      public long dividePlayers(int[] skill) {
        final int n = skill.length;
        int total = 0;
        int[] count = new int[2001];
        for (int s : skill) {
          total += s;
          count[s]++;
        }
    
        if (total % (n / 2) != 0) {
          return -1;
        }
    
        // skill of each team
        final int team = total / (n / 2);
        // number of player
        int seen = 0;
        long chemistry = 0;
        for (int i = 1; i < Math.min(team, 2001); i++) {
          if (count[i] != count[team - i]) {
            return -1;
          }
    
          if (i == team - i) {
            // player with same skill with even count
            if (count[i] % 2 != 0) {
              return -1;
            }
            chemistry += (long) count[i] / 2 * i * (team - i);
            seen += count[i];
          } else {
            chemistry += (long) count[i] * i * (team - i);
            seen += 2 * count[i];
          }
    
          count[i] = 0;
          count[team - i] = 0;
        }
    
        if (seen != n) {
          return -1;
        }
    
        return chemistry;
      }
    }
    

    Explain:

    nope.

    Complexity: