2581. Divide Players Into Teams Of Equal Skill¶
Difficulty: Medium
LeetCode Problem View on GitHub
2581. Divide Players Into Teams of Equal Skill
Medium
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:
2 <= skill.length <= 105skill.lengthis even.1 <= skill[i] <= 1000
Solution¶
class Solution {
public long dividePlayers(int[] skill) {
int n = skill.length;
Arrays.sort(skill);
int sum = 0, count = 0;
for (int ele : skill) sum += ele;
if (sum % (n / 2) != 0) return -1;
long ans = 0;
int req = sum / ( n / 2);
HashMap<Integer, Integer> map = new HashMap<>();
for (int ele : skill) map.put(ele, map.getOrDefault(ele, 0) + 1);
for (int i = 0; i < n; i++) {
int current = skill[i];
if (map.getOrDefault(current, 0) <= 0) continue;
int current_req = req - current;
if (current_req < 0) continue;
if (map.getOrDefault(current_req , 0) > 0) {
count++;
map.put(current_req, map.getOrDefault(current_req , 0) - 1);
map.put(current, map.getOrDefault(current, 0) - 1);
ans += (current * current_req);
}
}
if (count == n / 2) return ans;
return -1;
}
}
Complexity Analysis¶
- Time Complexity:
O(?) - Space Complexity:
O(?)
Approach¶
Detailed explanation of the approach will be added here