C++ O(N) keep track of # of balls to the right and left
See my latest update in repo LeetCode\n\n## Solution 1.\n\nAssume we are at s[i] and the corresponding operations needed is sum. When we move from s[i] to s[i +
See my latest update in repo [LeetCode](https://github.com/lzl124631x/LeetCode)\n\n## Solution 1.\n\nAssume we are at `s[i]` and the corresponding operations needed is `sum`. When we move from `s[i]` to `s[i + 1]`, if there are `left` balls that have indexes `<= i` and `right` balls that have indexes `> i`, then the number of operations needed for `s[i + 1]` will be `sum + left - right`.\n\n```cpp\n// OJ: https://leetcode.com/problems/minimum-number-of-operations-to-move-all-balls-to-each-box/\n// Author: github.com/lzl124631x\n// Time: O(N)\n// Space: O(1)\nclass Solution {\npublic:\n    vector<int> minOperations(string s) {\n        int N = s.size(), sum = 0, right = 0, left = 0;\n        vector<int> ans(s.size());\n        for (int i = 0; i < N; ++i) {\n            if (s[i] == \'1\') sum += i, ++right;\n        }\n        for (int i = 0; i < N; ++i) {\n            ans[i] = sum;\n            if (s[i] == \'1\') --right, ++left;\n            sum += left - right;\n        }\n        return ans;\n    }\n};\n```
[]