[LeetCode] Divide Players Into Teams of Equal Skill

2491. Divide Players Into Teams of Equal Skill

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class Solution {
public:
long long dividePlayers(vector<int>& A) {
if(A.size() % 2 == 1) return -1;
long long sum = 0, n = A.size(), div = n / 2;
unordered_map<int, int> freq;
for(auto a : A) {
sum += a;
freq[a] += 1;
}
if(sum % div) return -1;
long long target = sum / div;
long long res = 0;
for(auto a : A) {
if(!freq.count(a)) continue;
long long o = target - a;
if(!freq.count(o)) return -1;
res += o * a;
if(--freq[o] == 0) freq.erase(o);
if(!freq.count(a)) return -1;
if(--freq[a] == 0) freq.erase(a);
}
if(freq.size()) return -1;
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/12/04/PS/LeetCode/divide-players-into-teams-of-equal-skill/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.