Given a positive integer num
, you are allowed to swap any two digits with the same parity (any number of times). Your task is to return the largest possible number that can be obtained through these swaps.
Here is the Python implementation of the strategy:
def largestNumberByParitySwaps(num: int) -> int:
# Convert number to list of digits
digits = list(map(int, str(num)))
# Separate digits by parity
even_digits = sorted([d for d in digits if d % 2 == 0], reverse=True)
odd_digits = sorted([d for d in digits if d % 2 != 0], reverse=True)
# Variables to track the positions in sorted parity lists
even_idx, odd_idx = 0, 0
# Resultant list of digits
result_digits = []
for d in digits:
if d % 2 == 0:
# The next largest even digit
result_digits.append(even_digits[even_idx])
even_idx += 1
else:
# The next largest odd digit
result_digits.append(odd_digits[odd_idx])
odd_idx += 1
# Convert the list of digits back to integer
return int(''.join(map(str, result_digits)))
# Example usage:
print(largestNumberByParitySwaps(65875)) # Output should be the largest number obtained
num
.Overall, the time complexity is dominated by the sorting step, thus O(n log n).
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?