LeetCode/go/maximum-swap.go
2024-10-17 23:27:10 +02:00

46 lines
793 B
Go

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)
}