Minimum Number of Operations to Move All Balls to Each Box LeetCode solution in Python
1# Runtime: 68 ms (Top 97.39%) | Memory: 14.2 MB (Top 53.70%)2class Solution:3def minOperations(self, boxes: str) -> List[int]:4ans = [0] * len(boxes)5leftCount, leftCost, rightCount, rightCost, n = 0, 0, 0, 0, len(boxes)6for i in range(1, n):7if boxes[i - 1] == "1":8leftCount += 19leftCost += leftCount # each step move to right, the cost increases by # of 1s on the left10ans[i] = leftCost11for i in range(n - 2, -1, -1):12if boxes[i + 1] == "1":13rightCount += 114rightCost += rightCount15ans[i] += rightCost16return ans