P19854 [GeeksforGeeks] Minimum swaps required to group all 1s together2451
普及-
题目描述

Given an array of 0s and 1s, we need to write a program to find the minimum number of swaps required to group all 1s present in the array together.
Example 1:
Input : arr[ ] = {1, 0, 1, 0, 1}
Output : 1
Explanation:
Only 1 swap is required to group all 1's together.
Swapping index 1 and 4 will give arr[] = {1, 1, 1, 0, 0}.
Example 2:
Input : arr[ ] = {1, 0, 1, 0, 1, 1}
Output : 1

Your Task:
This is a function problem. The input is already taken care of by the driver code. You only need to complete the function minSwaps() that takes an array (arr), sizeOfArray (n) and return the minimum number of swaps required and if no 1's are present print -1. The driver code takes care of the printing.
Expected Time Complexity: O(N).
Expected Auxiliary Space: O(1).

Constraints:
1 ≤ N ≤ 10^{5}
0 ≤ Arr_{i} ≤ 1

输入格式

见题面

输出格式

见题面

样例输入
arr[ ] = {1, 0, 1, 0, 1}
样例输出
1