Divide Players Into Teams of Equal Skill

medium two pointers sorting greedy

Problem

You are given an even-length array skill of positive integers. Divide the players into n / 2 teams of two so that every team has the same total skill. A team's chemistry is the product of its two skills. Return the sum of all teams' chemistry, or -1 if no equal-total division exists.

Inputskill = [3,2,5,1,3,4]
Output22
Teams (1,5), (2,4), (3,3) each total 6. Chemistry = 1·5 + 2·4 + 3·3 = 22.
Inputskill = [1,1,2,3]
Output-1
No pairing gives every team the same total skill.

def divide_players(skill):
    skill.sort()
    n = len(skill)
    i, j = 0, n - 1
    target = skill[0] + skill[n - 1]
    total = 0
    while i < j:
        if skill[i] + skill[j] != target:
            return -1
        total += skill[i] * skill[j]
        i += 1
        j -= 1
    return total
function dividePlayers(skill) {
  skill.sort((a, b) => a - b);
  const n = skill.length;
  let i = 0, j = n - 1;
  const target = skill[0] + skill[n - 1];
  let total = 0;
  while (i < j) {
    if (skill[i] + skill[j] !== target) return -1;
    total += skill[i] * skill[j];
    i++;
    j--;
  }
  return total;
}
long dividePlayers(int[] skill) {
    Arrays.sort(skill);
    int n = skill.length;
    int i = 0, j = n - 1;
    int target = skill[0] + skill[n - 1];
    long total = 0;
    while (i < j) {
        if (skill[i] + skill[j] != target) return -1;
        total += (long) skill[i] * skill[j];
        i++;
        j--;
    }
    return total;
}
long long dividePlayers(vector<int>& skill) {
    sort(skill.begin(), skill.end());
    int n = skill.size();
    int i = 0, j = n - 1;
    int target = skill[0] + skill[n - 1];
    long long total = 0;
    while (i < j) {
        if (skill[i] + skill[j] != target) return -1;
        total += (long long) skill[i] * skill[j];
        i++;
        j--;
    }
    return total;
}
Time: O(n log n) Space: O(1)