LeetCode 2491: Divide Players Into Teams of Equal Skill

Problem Description

Explanation:

To solve this problem, we can follow these steps:

  1. Calculate the total sum of all player skills in the array.
  2. Sort the array of player skills in non-decreasing order.
  3. Iterate over the array, trying to pair players from the extremes (highest and lowest skills) to form teams with equal total skill.
  4. Calculate the chemistry of each team and sum them up. If all teams have the same total skill, return the sum of chemistry. Otherwise, return -1.

Time Complexity: Sorting the array takes O(nlogn) time. After sorting, iterating over the array takes O(n) time. So, the overall time complexity is O(nlogn).

Space Complexity: We are not using any extra space other than a few variables. Thus, the space complexity is O(1).

:

Solutions

class Solution {
    public int dividePlayersIntoTeams(int[] skill) {
        int n = skill.length;
        if (n % 2 != 0) {
            return -1; // Return -1 if the number of players is odd
        }
        
        Arrays.sort(skill);
        
        int sum = 0;
        for (int i = 0; i < n/2; i++) {
            sum += skill[i] * skill[n-1-i];
        }
        
        return sum;
    }
}

Loading editor...