Skip to content

Commit

Permalink
Sync LeetCode submission Runtime - 0 ms (100.00%), Memory - 9.5 MB (8…
Browse files Browse the repository at this point in the history
…5.11%)
  • Loading branch information
nathannaveen committed Mar 3, 2025
1 parent 4c1ce77 commit 73fcb9b
Show file tree
Hide file tree
Showing 2 changed files with 64 additions and 0 deletions.
38 changes: 38 additions & 0 deletions 1107-minimum-swaps-to-group-all-1s-together/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
<p>Given a&nbsp;binary array <code>data</code>, return&nbsp;the minimum number of swaps required to group all <code>1</code>&rsquo;s present in the array together in <strong>any place</strong> in the array.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>

<pre>
<strong>Input:</strong> data = [1,0,1,0,1]
<strong>Output:</strong> 1
<strong>Explanation:</strong> There are 3 ways to group all 1&#39;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.
</pre>

<p><strong class="example">Example 2:</strong></p>

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

<p><strong class="example">Example 3:</strong></p>

<pre>
<strong>Input:</strong> data = [1,0,1,0,1,0,0,1,1,0,1]
<strong>Output:</strong> 3
<strong>Explanation:</strong> One possible solution that uses 3 swaps is [0,0,0,0,0,1,1,1,1,1,1].
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
<li><code>1 &lt;= data.length &lt;= 10<sup>5</sup></code></li>
<li><code>data[i]</code> is either <code>0</code> or <code>1</code>.</li>
</ul>
26 changes: 26 additions & 0 deletions 1107-minimum-swaps-to-group-all-1s-together/solution.go
Original file line number Diff line number Diff line change
@@ -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
}

0 comments on commit 73fcb9b

Please sign in to comment.