Show problems as
Classic problem #670MediumMathGreedy

Maximum Swap

Real-world version: One Wheel Exchange
Tracked in this browser only
Read Maximum Swap on LeetCode(opens in a new tab)

The statement here is our own: the same inputs, outputs and technique.

A mechanical counter shows the value num on a row of digit wheels.

Maintenance is allowed one adjustment: pick two wheels and exchange the digits sitting in them. Making no exchange at all is also allowed.

Return the largest value the row can show once the adjustment is done. The row never gains or loses wheels, and the row is read as an ordinary number, so any leading zeros it ends up showing contribute nothing to the value.

Examples

Example 1

Input
num = 1993
Output
9913

Exchanging the 1 in the first wheel with the 9 in the third wheel leaves the row reading 9913.

Example 2

Input
num = 87654
Output
87654

Every exchange available here gives a value below 87654, so the row is left as it is.

Example 3

Input
num = 4020
Output
4200

Exchanging the 0 in the second wheel with the 2 in the third wheel leaves the row reading 4200.

Example 4

Input
num = 0
Output
0

A single wheel has nothing to exchange with, so the reading stays 0.

Constraints

  • 0 <= num <= 10^8

The signature

The editor starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.

Python
def maximum_swap(num: int) -> int:
Java
public int maximumSwap(int num)