imashutosh51

Minimum Number of Operations to Move All Balls to Each Box

Aug 30th, 2022 (edited)
119
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.28 KB | None | 0 0
  1. '''
  2.   Leetcode:
  3.   First to bring all the balls to 0th position will be the sum of all the balls indexes.
  4.   Assume at ith position,We need n opeation to shift all balls into ith box.
  5.   Let's assume we know all the balls in the left and right of ith position
  6.   as per the initial state.
  7.   so,in case of (i+1)th box,all the balls in the left of (i+1)th box will
  8.   move one more box than the ith box and all the balls in the right of (i+1)th
  9.   including (i+1)th box will move one less boxes.
  10.   so,
  11.   arr[i+1]=arr[i]+left-right(including current box)
  12. '''
  13. #Python
  14. from typing import List
  15.  
  16. class Solution:
  17.     def minOperations(self, boxes: str) -> List[int]:
  18.         n = len(boxes)
  19.         cur = 0 # initial cost for index 0
  20.         total_balls = 0
  21.         for i in range(n):
  22.             if boxes[i] == '1':
  23.                 cur += i
  24.                 total_balls += 1
  25.        
  26.         ans = [cur]
  27.         balls_left = 1 if boxes[0] == '1' else 0
  28.         balls_right = total_balls - balls_left
  29.        
  30.         for i in range(1, n):
  31.             cur = cur + balls_left - balls_right
  32.             ans.append(cur)
  33.            
  34.             # update counts
  35.             if boxes[i] == '1':
  36.                 balls_left += 1
  37.                 balls_right -= 1
  38.        
  39.         return ans
Advertisement
Add Comment
Please, Sign In to add comment