[LeetCode] 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.

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

划分技能点相等的团队。

给你一个正整数数组 skill ,数组长度为 偶数 n ,其中 skill[i] 表示第 i 个玩家的技能点。将所有玩家分成 n / 2 个 2 人团队,使每一个团队的技能点之和 相等 。

团队的 化学反应 等于团队中玩家的技能点 乘积 。

返回所有团队的 化学反应 之和,如果无法使每个团队的技能点之和相等,则返回 -1 。

思路

注意题目的题设,如果 input 数组最后是能组成 n / 2 组团队且每一个团队的技能点之和相等的话,那么技能点的和 sum = 最小的玩家技能点 + 最大的玩家技能点。所以这里我们可以将 input 数组排序,然后用双指针的方式从两边往中间逼近。如果有任何一组技能点的和 != sum则说明配对失败,返回 -1。

注意题目的数据范围,res 要用 long 类型,否则会溢出。

复杂度

时间O(nlogn)
空间O(1)

代码

Java实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
public long dividePlayers(int[] skill) {
int n = skill.length;
int[] sorted = skill.clone();
Arrays.sort(sorted);
int left = 0;
int right = n - 1;
int sum = sorted[0] + sorted[n - 1];
long res = 0;
while (left < right) {
int l = sorted[left++];
int r = sorted[right--];
if (l + r != sum) {
return -1;
} else {
res += l * r;
}
}
return res;
}
}

[LeetCode] 2491. Divide Players Into Teams of Equal Skill
https://shurui91.github.io/posts/3764186800.html
Author
Aaron Liu
Posted on
October 4, 2024
Licensed under