All problems
0363MediumMathGreedy

One Wheel Exchange

Tracked in this browser only
Write code

Trains the technique from

LeetCode 670Maximum Swap

This is an original problem, written from a brief that listed the technique, the difficulty, the topics, the function shape and the input bounds — none of that problem's wording, examples, hints or editorials. The link is there so you can map your practice onto the standard set.

Same function shape, different story and different numbers.

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 is preloaded with this. It matches the parent problem's shape, so a solution that works here transfers to a judge unchanged.

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