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實現
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;
}
}