Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- '''
- Leetcode:
- First to bring all the balls to 0th position will be the sum of all the balls indexes.
- Assume at ith position,We need n opeation to shift all balls into ith box.
- Let's assume we know all the balls in the left and right of ith position
- as per the initial state.
- so,in case of (i+1)th box,all the balls in the left of (i+1)th box will
- move one more box than the ith box and all the balls in the right of (i+1)th
- including (i+1)th box will move one less boxes.
- so,
- arr[i+1]=arr[i]+left-right(including current box)
- '''
- #Python
- from typing import List
- class Solution:
- def minOperations(self, boxes: str) -> List[int]:
- n = len(boxes)
- cur = 0 # initial cost for index 0
- total_balls = 0
- for i in range(n):
- if boxes[i] == '1':
- cur += i
- total_balls += 1
- ans = [cur]
- balls_left = 1 if boxes[0] == '1' else 0
- balls_right = total_balls - balls_left
- for i in range(1, n):
- cur = cur + balls_left - balls_right
- ans.append(cur)
- # update counts
- if boxes[i] == '1':
- balls_left += 1
- balls_right -= 1
- return ans
Advertisement
Add Comment
Please, Sign In to add comment