Given an array of tasks (numbers 1 to n) output the most balance load of work between 2 servers
tasks[1,1,1,5,3]. Output should be [5,6] or [6,5]
The idea behind the solution is simple. Keep track of current load of each server and everytime one is unbalanced try to put some task in ORDER to balance it.
public static int[] loadServers(int[] tasks){
int serverA = 0;
int serverB = 0;
int[] result = new int[2];//here we will store final loads in servers A & B
//EDGE CASES
if(tasks.length == 0) return result;
if(tasks.length == 1){
serverA += tasks[0];
result[0] = serverA;
}
Arrays.sort(tasks);
//GENERAL WORK
int L = 0;
int R = tasks.length - 1;
while(L <= R){
System.out.println("serverA: "+serverA);
System.out.println("serverB: "+serverB);
System.out.println("-->dif: "+Math.abs(serverA-serverB));
if(serverA <= serverB){
serverA += tasks[L];
L++;
}
else if(serverA > serverB){
serverB += tasks[R];
R--;
}
}
//BUILD RESULT
result[0] = serverA;
result[1] = serverB;
return result;
}