Problem List
You're given a four-digit positive integer. You need to split those digits into two new numbers using every digit exactly once. Leading zeroes are allowed. Return the minimum possible sum of the two new numbers.
O(1) Constant time since input is fixed at 4 digits.O(1)A slice of 4 ints and a few vars.With only four digits, it’s easy to spot the greedy pattern: pair the smallest digits into tens places.
In hindsight, I'd probably just use a slice of fixed length and sort it next time, much simpler and more readable.
func minimumSum(num int) int {
var arr []int
for num > 0 {
arr = append(arr, num%10)
num /= 10
}
low1, arr := minValAndMaxArr(arr)
low2, arr := minValAndMaxArr(arr)
return low1 * 10 + low2 * 10 + arr[0] + arr[1]
}
func minValAndMaxArr(arr []int) (int, []int) {
min := arr[0]
idx := 0
for i := 1; i < len(arr); i++ {
if arr[i] < min {
min = arr[i]
idx = i
}
}
arr = append(arr[:idx], arr[idx+1:]...)
return min, arr
}