[translate by ChatGPT]
This was practice using a lambda functionm abd count_if, and accumulate.
Code
class Solution {
public:
vector<int> minOperations(string boxes) {
// ans(i) = sum of |j-i|, for each boxes(j) = 1
// |j-i| = (j-i) if (j>i) else (i-j)
// ans(0) = sum of j, for each boxes(j) = 1
int cntL = 0;
int cntR = std::count_if(boxes.begin(), boxes.end(), [](char value) {return value =='1';});
int sum = std::accumulate(boxes.begin(), boxes.end(), 0,
[&, index = 0](int acc, char value) mutable {
int result = acc;
if (value == '1') {
result += index;
}
++index; // Increment the index
return result;
});
vector<int> ans;
for(int i = 0 ; i < boxes.size() ; ++i){
ans.push_back(sum);
if(boxes[i] == '1') {
++cntL;
--cntR;
}
sum -= cntR;
sum += cntL;
}
return ans;
}
};