Load Balancer Problem
Solve another SPOJ problem based on the Greedy approach.
We'll cover the following
Problem statement
SuperComputer Inc. has built a super-fast computer server consisting of N
hyper-scalar lightning-fast processors. These processors are numbered from 1
to N
and are used to process independent jobs. Every new incoming job is assigned to an arbitrary processor. Sometimes, a processor may be assigned too many jobs while other processors have a relatively light load (or even wait idly). In that case, the whole system undergoes re-balancing.
Re-balancing proceeds in rounds. In each round, every processor can transfer at most one job to each of its neighbors on the bus. Neighbors of the processor i
are the processors i - 1
and i + 1
(processors 1
and N
have only one neighbor each, 2
and N - 1
respectively). The goal of re-balancing is to make all processors have the same number of jobs.
Given the number of jobs initially assigned to each processor, you are asked to determine the minimal number of rounds needed to achieve the state when every processor has the same number of jobs or to determine that such re-balancing is not possible.
Solution: Greedy approach
We can apply the Greedy approach to solve this problem. First, we need to find the load that each processor will have. We can find it by summing all the elements of the array and then dividing the sum by the total number of elements. Let us call it load
.
So at the final state, each processor will have the load = load
.
Now, we can partition the array and find the amount of load that is to be shared between these two partitions. The answer will be the maximum of all the loads shared between all the partitions.
Let us now move on to the implementation.
Level up your interview prep. Join Educative to access 80+ hands-on prep courses.