Maximum Swap

Medium Topics Company Tags

You may exchange two decimal digits of the nonnegative integer num at most once. Return the largest integer obtainable. You may also leave the digits unchanged.

Example 1:

Input: num = 1993

Output: 9913

Explanation: Swap the first digit with the rightmost 9 to obtain 9913. Using the other 9 would produce only 9193.

Example 2:

Input: num = 98368

Output: 98863

Explanation: Swap the digit 3 with the final 8 to obtain 98863. The earlier 9 and 8 already form the largest possible prefix.

Example 3:

Input: num = 0

Output: 0

Explanation: The only digit is 0, so there is no pair to swap and the result remains 0.

Constraints:

  • 0 <= num <= 100000000


Topics

Company Tags

Please upgrade to NeetCode Pro to view company tags.