---
# System prepended metadata

title: 2491. Divide Players Into Teams of Equal Skill
tags: [Leetcode, Two Sum, HashMap, Medium]

---

# 2491. Divide Players Into Teams of Equal Skill
###### tags: `Leetcode` `Medium` `HashMap` `Two Sum`
Link: https://leetcode.com/problems/divide-players-into-teams-of-equal-skill/
## 思路
two sum 找出和等于```sum/(n/2)```的所有pair
## Code
```java=
class Solution {
    public long dividePlayers(int[] skill) {
        int n = skill.length;
        long ans = 0;
        long sum = 0;
        for(int i=0; i<n; i++) sum += skill[i];
        if(sum%(n/2)!=0) return -1; 
        int teamSkill = (int)(sum/(n/2));
        Map<Integer, Integer> cnt = new HashMap<>();
        for(int i=0; i<n; i++){
            if(cnt.containsKey(teamSkill-skill[i])){
                ans += skill[i]*(teamSkill-skill[i]);
                cnt.put(teamSkill-skill[i], cnt.get(teamSkill-skill[i])-1);
                if(cnt.get(teamSkill-skill[i])==0) cnt.remove(teamSkill-skill[i]);
            }
            else cnt.put(skill[i], cnt.getOrDefault(skill[i], 0)+1);
        }
        return cnt.size()!=0?-1:ans;
    }
}
```