go: add «670. Maximum Swap»

URL:	https://leetcode.com/problems/maximum-swap/
Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
Matej Focko 2024-10-17 23:27:10 +02:00
parent 151eb4878b
commit 5f10fcee50
Signed by: mfocko
SSH key fingerprint: SHA256:icm0fIOSJUpy5+1x23sfr+hLtF9UhY8VpMC7H4WFJP8

46
go/maximum-swap.go Normal file
View file

@ -0,0 +1,46 @@
package main
func maximumSwap(num int) int {
fromInt := func() (int, []int) {
digits := make([]int, 9)
i := 0
for ; num > 0; i++ {
digits[i] = num % 10
num /= 10
}
return i, digits
}
toInt := func(digits []int) int {
result := 0
for i := len(digits) - 1; i >= 0; i-- {
result *= 10
result += digits[i]
}
return result
}
length, digits := fromInt()
for i := length - 1; i > 0; i-- {
max_index := i - 1
for j := i - 1; j >= 0; j-- {
if digits[j] > digits[i] && digits[j] >= digits[max_index] {
max_index = j
}
}
// found bigger digit that can be swapped
if digits[max_index] > digits[i] {
digits[max_index], digits[i] = digits[i], digits[max_index]
return toInt(digits)
}
}
// no swaps happened
return toInt(digits)
}