Skip to content

Latest commit

 

History

History

2491

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 

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 <= 105
  • skill.length is even.
  • 1 <= skill[i] <= 1000

Companies: Expedia

Related Topics:
Array, Hash Table, Two Pointers, Sorting

Similar Questions:

Solution 1.

// OJ: https://leetcode.com/problems/divide-players-into-teams-of-equal-skill
// Author: github.com/lzl124631x
// Time: O(NlogN)
// Space: O(1)
class Solution {
public:
    long long dividePlayers(vector<int>& A) {
        sort(begin(A), end(A));
        long long ans = 0, sum = A[0] + A.back();
        for (int i = 0, j = A.size() - 1; i < j; ++i, --j) {
            if (A[i] + A[j] != sum) return -1;
            ans += (long long)A[i] * A[j];
        }
        return ans;
    }
};