Given a binary array data, you need to find the minimum number of swaps required to group all the 1's together in any contiguous block within the array.
A swap involves exchanging any two elements in the array. The goal is to create a contiguous subarray containing all the 1's with the fewest possible swaps.
Example: In array [1, 0, 1, 0, 1], we have 3 ones. We need to find a window of size 3 where we can group all ones together with minimum swaps. The optimal window might be positions 1-3, requiring us to swap the 0's with 1's from outside this window.
Key insight: Since we want all ones together, we need to find the best contiguous window of size equal to the total number of ones, then count how many zeros are in that window - those zeros need to be swapped out.
Input & Output
Constraints
- 1 โค data.length โค 105
- data[i] is either 0 or 1
- The array contains at least one element