I am stuck with a problem and I need some help from bright minds of SO. I want to divide n players to m teams. Each player has different game abilities. Abilities are represented by positive or negative integers. A team's total ability is simply the sum of the ability scores of the people assigned to that team.
My goal is to find the minimum possible difference between the team with the maximum total ability and the team with the minimum total ability. The constraints are each player must be placed on a team and every team must have at least one member.
For example if I have the following player with abilities: [1, 2, 3, 4, 5, 6, 7] and want to form three teams. So the min possible difference between the team with the maximum total ability and the team with the minimum total ability is 1. One possible solution is:
Team 1: 1 + 3 + 6 = 10
Team 2: 2 + 7 = 9
Team 3: 4 + 5 = 9
I have tried to divide the players by using the following strategy:
1.sort the abilities
2.each time assign the remained highest ability player to the group with lowest ability until there is no players
This strategy works for some problems. Here is the code I had so far:
public int minDifference(int numTeams, int[] abilities) {
ArrayList<ArrayList<Integer>> teams = new ArrayList<ArrayList<Integer>>();
int[] teamSum = new int[numTeams];
for(int i = 0; i < numTeams; i++){
teams.add(new ArrayList<Integer>());
teamSum[i] = 0;
}
Arrays.sort(abilities);
for(int i = abilities.length - 1; i >= 0; i--){
int minSum = teamSum[0];
int minNum = 0;
for(int j = 1; j < numTeams; j++){
if(teamSum[j] < minSum){
minSum = teamSum[j];
minNum = j;
}
}
teams.get(minNum).add(abilities[i]);
teamSum[minNum] += abilities[i];
}
Arrays.sort(teamSum);
System.out.println(teamSum[numTeams - 1] - teamSum[0]);
return teamSum[numTeams - 1] - teamSum[0];
}
Now I am stuck. My idea is to compare two teams. Say A and B. Player Tom from A and Jerry from B. If A - B = 10, and Tom - Jerry = 3; then swap Tom and Jerry. So A - B = 4 now. And keep doing this. But it seems there are too many compares(because you also need to calculate the difference between players in two teams) and I don't know when to stop(means how can I know it is the minimum).