2491. Divide Players Into Teams of Equal Skill
Difficulty: Medium
Topics: Array, Hash Table, Two Pointers, Sorting
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:
Example 2:
Example 3:
Constraints:
Hint:
Solution:
We can follow the hint provided and use a greedy approach. Here's the detailed breakdown of the solution:
Sort the Skill Array: Sorting allows us to efficiently pair the weakest player (smallest value) with the strongest player (largest value).
Check for Valid Pairing: The sum of the skills of each team should be equal. After sorting, we will pair the smallest and the largest element, then the second smallest with the second largest, and so on. If at any point, the sum of a pair differs from the previous sums, it's impossible to divide the players into valid teams, and we should return -1.
Calculate the Chemistry: The chemistry of each team is the product of the two skills in that team. Sum up all the chemistry values for each valid team.
Return the Total Chemistry: If all the teams have the same total skill, return the sum of their chemistry.
Let's implement this solution in PHP: 2491. Divide Players Into Teams of Equal Skill
/**
// Test cases
$skill1 = [3, 2, 5, 1, 3, 4];
$skill2 = [3, 4];
$skill3 = [1, 1, 2, 3];
echo dividePlayers($skill1) . "\n"; // Output: 22
echo dividePlayers($skill2) . "\n"; // Output: 12
echo dividePlayers($skill3) . "\n"; // Output: -1
?>
Sorting: The array skill is sorted to ensure that we can efficiently pair the smallest and largest values.
Two Pointers: We use two pointers ($i starting from the beginning and $j starting from the end). For each valid pair (smallest and largest), we check if their sum is the same as the expected teamSkillSum. If not, it's impossible to divide the players into teams.
Chemistry Calculation: If the pair is valid, the chemistry is calculated as the product of the two values ($skill[$i] * $skill[$j]), and we keep adding it to the total chemistry.
Edge Cases:
This solution works within the given constraint of up to 105 players.
Contact Links
Si vous avez trouvé cette série utile, pensez à donner une étoile au référentiel sur GitHub ou à partager la publication sur vos réseaux sociaux préférés ?. Votre soutien signifierait beaucoup pour moi !
Si vous souhaitez du contenu plus utile comme celui-ci, n'hésitez pas à me suivre :
The above is the detailed content of Divide Players Into Teams of Equal Skill. For more information, please follow other related articles on the PHP Chinese website!