diff --git a/1107-minimum-swaps-to-group-all-1s-together/README.md b/1107-minimum-swaps-to-group-all-1s-together/README.md new file mode 100644 index 0000000..7cf59fa --- /dev/null +++ b/1107-minimum-swaps-to-group-all-1s-together/README.md @@ -0,0 +1,38 @@ +

Given a binary array data, return the minimum number of swaps required to group all 1’s present in the array together in any place in the array.

+ +

 

+

Example 1:

+ +
+Input: data = [1,0,1,0,1]
+Output: 1
+Explanation: There are 3 ways to group all 1's together:
+[1,1,1,0,0] using 1 swap.
+[0,1,1,1,0] using 2 swaps.
+[0,0,1,1,1] using 1 swap.
+The minimum is 1.
+
+ +

Example 2:

+ +
+Input: data = [0,0,0,1,0]
+Output: 0
+Explanation: Since there is only one 1 in the array, no swaps are needed.
+
+ +

Example 3:

+ +
+Input: data = [1,0,1,0,1,0,0,1,1,0,1]
+Output: 3
+Explanation: One possible solution that uses 3 swaps is [0,0,0,0,0,1,1,1,1,1,1].
+
+ +

 

+

Constraints:

+ + diff --git a/1107-minimum-swaps-to-group-all-1s-together/solution.go b/1107-minimum-swaps-to-group-all-1s-together/solution.go new file mode 100644 index 0000000..2e95fba --- /dev/null +++ b/1107-minimum-swaps-to-group-all-1s-together/solution.go @@ -0,0 +1,26 @@ +func minSwaps(data []int) int { + oneCounter, maximum, counter := 0, 0, 0 + + for _, i := range data { + oneCounter += i + } + + for i := 0; i < oneCounter; i++ { + counter += data[i] + } + maximum = max(maximum, counter) + + for i := oneCounter; i < len(data); i++ { + counter += data[i] - data[i - oneCounter] + maximum = max(maximum, counter) + } + + return oneCounter - maximum +} + +func max(a, b int) int { + if a > b { + return a + } + return b +}