# 1769. Minimum Number of Operations to Move All Balls to Each Box ###### tags: `Leetcode` `Medium` `Greedy` `Three Pass` Link: https://leetcode.com/problems/minimum-number-of-operations-to-move-all-balls-to-each-box/description/ ## 思路 ```leftCnt```记录把左边每一个ball搬过来需要多少operation ```rightCnt```记录把右边每一个ball搬过来需要多少operation ```leftCnt[i] = leftCnt[i-1]+左边一共有多少个ball``` ## Code ```java= class Solution { public int[] minOperations(String boxes) { int n = boxes.length(); int[] leftCnt = new int[n]; int cnt = 0; for(int i=1; i<n; i++){ cnt += boxes.charAt(i-1)=='1'?1:0; leftCnt[i] = leftCnt[i-1]+cnt; } int[] rightCnt = new int[n]; cnt = 0; for(int i=n-2; i>=0; i--){ cnt += boxes.charAt(i+1)=='1'?1:0; rightCnt[i] = rightCnt[i+1]+cnt; } int[] ans = new int[n]; for(int i=0; i<n; i++){ ans[i] = leftCnt[i]+rightCnt[i]; } return ans; } } ```