Created
May 1, 2025 01:34
-
-
Save masmerino13/b2b0d4194153c31ec02750928b2cd464 to your computer and use it in GitHub Desktop.
get the smallest binary string
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
) | |
func smallestBinaryStringWithSwaps(s string, maxSwaps int) string { | |
runes := []rune(s) | |
n := len(runes) | |
for i := 0; i < n-1 && maxSwaps > 0; { | |
if runes[i] > runes[i+1] { | |
runes[i], runes[i+1] = runes[i+1], runes[i] | |
maxSwaps-- | |
if i > 0 { | |
i-- | |
} | |
} else { | |
i++ | |
} | |
} | |
return string(runes) | |
} | |
func main() { | |
s := "1101101" | |
maxSwaps := 5 | |
result := smallestBinaryStringWithSwaps(s, maxSwaps) | |
fmt.Println("smallest bynary string:", result) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment