Given a positive integer num
, split it into two non-negative integers num1
and num2
such that:
num1
and num2
in any order forms the number num
.The task is to find the combination of num1
and num2
such that their sum is minimized.
num = 4325
59
4325
is into num1 = 42
and num2 = 35
, resulting in 42 + 35 = 77
. But the better split is num1 = 25
and num2 = 34
, resulting in 25 + 34 = 59
.num1
and num2
have leading zeros?
num1
or num2
be zero?
num
be maintained in the split?
num1
and num2
to minimize their sum.num1
and num2
such that num1
takes the smallest remaining digit first, followed by num2
, and so forth. This tends to balance the magnitude of both numbers, minimizing their sum.def split_with_minimum_sum(num: int) -> int:
# Step 1: Extract and sort the digits
digits = sorted([int(digit) for digit in str(num)])
# Step 2: Initialize the two numbers
num1, num2 = 0, 0
# Step 3: Distribute the digits
for i, digit in enumerate(digits):
if i % 2 == 0:
num1 = num1 * 10 + digit
else:
num2 = num2 * 10 + digit
# Step 4: Return the sum of num1 and num2
return num1 + num2
# Example usage
print(split_with_minimum_sum(4325)) # Output: 59
This ensures the solution is efficient even for larger values of num
.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?