``````class Solution {
public:
vector<int> minOperations(string boxes) {
int n = boxes.size();
vector<int> res;
for(int i = 0;i < n;i++)
{
int distance = 0;
for(int j = 0;j < n;j++)
{
if(i == j) continue;
if('1' == boxes[j])
distance += abs(i-j);
}
res.push_back(distance);
}
return res;
}
};``````

``````Runtime: 144 ms, faster than 39.87% of C++ online submissions for Minimum Number of Operations to Move All Balls to Each Box.
Memory Usage: 9.3 MB, less than 39.10% of C++ online submissions for Minimum Number of Operations to Move All Balls to Each Box.``````

``````vector<int> minOperations(string boxes) {
vector<int> res(boxes.length());
for (int i = 0, ops = 0, cnt = 0; i < boxes.length(); ++i) {
res[i] += ops;
cnt += boxes[i] == '1' ? 1 : 0;
ops += cnt;
}
for (int i = boxes.length() - 1, ops = 0, cnt = 0; i >= 0; --i) {
res[i] += ops;
cnt += boxes[i] == '1' ? 1 : 0;
ops += cnt;
}
return res;
}``````

``````Runtime: 4 ms, faster than 96.14% of C++ online submissions for Minimum Number of Operations to Move All Balls to Each Box.
Memory Usage: 8.7 MB, less than 91.82% of C++ online submissions for Minimum Number of Operations to Move All Balls to Each Box.``````

``````class Solution {
public int[] minOperations(String boxes) {
int left = 0, right = 0, total = 0;//左边盒子的个数，右边盒子的个数，操作数
//计算第一个盒子的操作数
if (boxes.charAt(0) == '1') left ++;
for (int i = 1 ; i < boxes.length(); i++) {
if (boxes.charAt(i) == '1') {
right++;
total += i;
}
}
//根据前一个盒子的操作数，计算下一个盒子的操作数
for (int i = 1; i < boxes.length(); i++) {
total = total + left - right;
if (boxes.charAt(i) == '1') {
left ++;
right --;
}
}
}
}``````

``````Runtime: 4 ms, faster than 96.14% of C++ online submissions for Minimum Number of Operations to Move All Balls to Each Box.
Memory Usage: 8.7 MB, less than 91.82% of C++ online submissions for Minimum Number of Operations to Move All Balls to Each Box.``````