🏆🥇 Beats 100% ||  C++ || Prefix Sum || Beginner Friendly🔥🌟
Intuition🧠The goal is to calculate the minimum number of operations needed to move all the balls ('1') to each box. Instead of recalculating the cost for each b
# Intuition🧠
The goal is to calculate the minimum number of operations needed to move all the balls ('1') to each box. Instead of recalculating the cost for each box independently (which would be inefficient), we can use a prefix-sum-like approach:

1️⃣ **First Pass**
- Start by calculating the total cost (sum) for the first box.
- Every time we encounter a '1', "sub" increases by 1 because each '1' starts contributing one less operation as we move right.

2️⃣ **Second Pass**
- Using the initial sum, calculate the cost for each subsequent box by adjusting it dynamically using the "sub" variable.
- Every box reuses the previous result "sum" to avoid recalculating the total from scratch.
- If the current box contains '1', update "sub" to account for the shift in ball contributions. As we see, when passing '1' we do not need to decrease the distance again, moreover we need to add 1 to the distance. ->`sub -= 2`

# Approach🚀
1. Calculate the initial sum and "sub" while iterating through the boxes.

1. Store the initial cost for the first box.

1. For each subsequent box:
- Update the cost by reducing it based on "sub".
- Adjust "sub" when encountering '1'.


# Complexity
- Time complexity: O(n) 🕒
Each box is visited twice (once per pass).

- Space complexity: O(n) 💾
To store the result array.

![image.png](https://assets.leetcode.com/users/images/de4374ce-6f1f-4ff4-b3d6-b242e38c5af5_1736144722.1765256.png)


# Code
```cpp []
class Solution {
public:
    vector<int> minOperations(string boxes) {
        int sub = 0;
        int sum = 0;
        vector<int>res (boxes.size(), 0);
        for(int i = 0; i < boxes.size(); i++){
            if(boxes[i] == '1'){
                sub += 1;
                sum += i;
            }
        }
        if(boxes[0] == '1'){
            sub -= 2;
        }
        int pos = 0;
        res[pos++] = sum;
        for(int i = 1; i < boxes.size(); i++){
            sum = sum - sub;
            if(boxes[i] == '1'){sub-=2;}
            res[pos++] = sum;
        }
        return res;
    }
};
```
['Array', 'String', 'Prefix Sum', 'C++']