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%)
2
class Solution:
3
def minOperations(self, boxes: str) -> List[int]:
4
ans = [0] * len(boxes)
5
leftCount, leftCost, rightCount, rightCost, n = 0, 0, 0, 0, len(boxes)
6
for i in range(1, n):
7
if boxes[i - 1] == "1":
8
leftCount += 1
9
leftCost += leftCount # each step move to right, the cost increases by # of 1s on the left
10
ans[i] = leftCost
11
for i in range(n - 2, -1, -1):
12
if boxes[i + 1] == "1":
13
rightCount += 1
14
rightCost += rightCount
15
ans[i] += rightCost
16
return ans

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0