2491. Divide Players Into Teams of Equal Skill #663
-
Topics: You are given a positive integer array 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 Example 1:
Example 2:
Example 3:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We can follow the hint provided and use a greedy approach. Here's the detailed breakdown of the solution: Steps:
Let's implement this solution in PHP: 2491. Divide Players Into Teams of Equal Skill <?php
/**
* @param Integer[] $skill
* @return Integer
*/
function dividePlayers($skill) {
// Sort the skill array
sort($skill);
// Initialize variables
$n = count($skill);
$totalChemistry = 0;
$teamSkillSum = $skill[0] + $skill[$n - 1]; // Expected team sum
// Two-pointer approach to form teams
for ($i = 0, $j = $n - 1; $i < $j; $i++, $j--) {
// Check if the team formed by skill[i] and skill[j] has the correct sum
if ($skill[$i] + $skill[$j] != $teamSkillSum) {
return -1; // Teams can't be formed with equal total skill
}
// Add the chemistry of the team to the total
$totalChemistry += $skill[$i] * $skill[$j];
}
// Return the total chemistry of all the teams
return $totalChemistry;
}
// 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
?> Explanation:
Time Complexity:
This solution works within the given constraint of up to |
Beta Was this translation helpful? Give feedback.
We can follow the hint provided and use a greedy approach. Here's the detailed breakdown of the solution:
Steps:
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…