LeetCode 2491: Divide Players Into Teams of Equal Skill
Problem Description
Explanation:
To solve this problem, we can follow these steps:
- Calculate the total sum of all player skills in the array.
- Sort the array of player skills in non-decreasing order.
- Iterate over the array, trying to pair players from the extremes (highest and lowest skills) to form teams with equal total skill.
- Calculate the chemistry of each team and sum them up. If all teams have the same total skill, return the sum of chemistry. Otherwise, return -1.
Time Complexity: Sorting the array takes O(nlogn) time. After sorting, iterating over the array takes O(n) time. So, the overall time complexity is O(nlogn).
Space Complexity: We are not using any extra space other than a few variables. Thus, the space complexity is O(1).
:
Solutions
class Solution {
public int dividePlayersIntoTeams(int[] skill) {
int n = skill.length;
if (n % 2 != 0) {
return -1; // Return -1 if the number of players is odd
}
Arrays.sort(skill);
int sum = 0;
for (int i = 0; i < n/2; i++) {
sum += skill[i] * skill[n-1-i];
}
return sum;
}
}
Loading editor...