-4

There are N teams in a software company. The ith team has Bi employees in it and a total budget of Ai units of money. Each team has to divide their budget within employees equally. But for some teams it's not possible. Therefore the company has to perform revisions in their teams' budget. In one revision, to revise the budget of ith team, the budget of first i teams has to be increased by 1. Your task is to find the minimum number of revisions needed so that for each team, equal distribution of their budget among the employees are possible.

Sample case: (A1 B1), (A2 B2), (A3 B3) : (1 1), (3 7), (5 4).

Solution is 4. Initial budget (1,3,5) -> (2,4,5) -> (5,7,8)

Nilesh
  • 1,388
  • 6
  • 17

1 Answers1

2

The given problem can be solved by a constructive solution. To start off, let's inci denote the amount to be incremented for every Ai such that the sum (Ai + inci) can be distributed equally within Bi employees. The two observations to be made here are:

  • (Ai + inci) mod Bi should be equal to 0 for the amount to be distributed equally
  • inci <= inci-1, since we're always incrementing the budget in a prefix fashion starting from index 1 and hence it's impossible to have inci > inci-1 since inci-1 will always be incremented before inci

Using these two observations, we can start iterating over the given array from right-to-left and at every step we determine the value for inci. The value of inci should be (c * Bi - Ai), where c is a smallest integral value such that c * Bi >= Ai and (c * Bi - Ai) >= inci+1 the value for which can be calculated in O(1), since we can reform the equation to estimate the value of c, -

  • c >= (Ai / Bi)
  • c >= (Ai + inci+1) / Bi

Hence c = max(ceil(Ai / Bi), ceil((Ai + inci+1) / Bi)

Hence the overall complexity of the given solution is O(n) and the final solution is the value of inc1 (assuming 1-indexing)

Nilesh
  • 1,388
  • 6
  • 17