
Let ‘ARR’ = [ 0, 1, 0, 1]. We can group all 1s together in the following ways: ‘ARR’ =[0, 0, 1, 1] or ‘ARR’ = [0, 1, 1, 0].
In this example, we need only 1 swap to group all 1’s together which is the minimum possible.
The first line of input contains an integer ‘T’ which denotes the number of test cases.
The first line of each test case contains a single integer ‘N’ representing the number of elements in the array/list ‘ARR’.
The next line of each test case contains ‘N’ single space-separated integers (0s and 1s) denoting the elements of ‘ARR’.
For each test case, return the minimum number of swaps required to group all 1’s together.
You don't need to print anything, it has already been taken care of. Just implement the given function.
1 <= ‘T’ <= 100
2 <= ‘N’ <= 5000
0 <= ‘ARR[i]’ <= 1
Where ‘ARR[i]’ represents the elements of array/list ‘ARR’.
Time Limit: 1 sec
First, we traverse through ‘ARR’ and count the number of 1s presents. We store the count in a 'COUNTONE' variable. If 'COUNTONE' is 0 then we simply return -1.
Else, we have to find a subarray of length 'COUNTONE', which contains maximum number 1's. We then need to swap all the 0s with 1s present in that subarray of length 'COUNTONE' as it will result in minimum possible swaps.
The steps are as follows:
We can optimize our algorithm. Our main task is to find a subarray of length ‘COUNTONE’, which contains the maximum number of 1s. For that, we can use the sliding window technique.
First, we traverse 'ARR' from beginning to ‘COUNTONE’ and store numbers of 1s in the variable 'MAXNUMONE'. Now, we slide the ‘COUNTONE’ sized window to the end of the ‘ARR’ and find numbers of 1s in every window. If we get the number of 1s greater than 'MAXNUMONE' then we update 'MAXNUMONE'.
The steps are as follows: