Program to find minimum number of operations to move all balls to each box in Python



Suppose we have a binary string called boxes, where boxes[i] is '0' indicates the ith box is empty, and '1' indicates it contains one ball. Now, in one operation, we can move one ball from a box to an adjacent box. After doing so, there may be more than one ball in some boxes. We have to find an array answer of size n, where answer[i] is the minimum number of operations needed to move all the balls to the ith box.

So, if the input is like boxes = "1101", then the output will be [4, 3, 4, 5]

  • To put all balls on first box, we have to take from box2 with one operation and from last ball by three operations, so total 4 operations.

  • To put all balls on second box, we have to take from box1 with one operation and from last ball by two operations, so total 3 operations.

  • To put all balls on third box, we have to take from box2 and last with one operation each and from box1 by two operations, so total 4 operations.

  • To put all balls on last box, we have to take from box1 with three operations and from box2 with two operations, so total 5 operations.

To solve this, we will follow these steps −

  • left := 0, right := 0, dist := 0

  • for i in range 0 to size of boxes - 1, do

    • if boxes[i] is same as "1", then

      • dist := dist + i

      • if i is same as 0, then

        • left := left + 1

      • otherwise,

        • right := right + 1

  • arr := a list and initially put dist into it

  • for i in range 1 to size of boxes - 1, do

    • insert arr[i-1] + left - right at the end of arr

    • if boxes[i] is same as "1", then

      • left := left + 1

      • right := right - 1

  • return arr

Example

Let us see the following implementation to get better understanding −

def solve(boxes):    left = 0    right = 0    dist = 0    for i in range(len(boxes)):       if boxes[i] == "1":          dist += i          if i == 0:             left += 1          else:             right += 1 arr = [dist] for i in range(1, len(boxes)): arr.append(arr[i-1] + left - right) if boxes[i] == "1": left += 1 right -= 1 return arr boxes = "1101" print(solve(boxes))

Input

"1101" 

Output

[4, 3, 4, 5]
Updated on: 2021-10-06T08:51:33+05:30

779 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements