Maximum Swap

You are given an integer num. You may swap two of its digits at most once. Return the largest number you can get.

30:00

Maximum Swap
medium
Free written solution
Topics
Companies

You are given an integer num. You may swap two of its digits at most once. Return the largest number you can get.

Example 1:
Input: {"num":2736}
Output: 7236
Constraints:
  • 0≤num≤1080 \leq \text{num} \leq 10^8

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"num":2736}

We may swap two digits of 2736 once. A bigger digit moved to the front adds the most value.

2

0

.

7

1

.

3

2

.

6

3

.

last[d]: rightmost position of digit d (probed from 9 down)

9

-

8

-

7

-

6

-

5

-

4

-

3

-

2

-

1

-

0

-

original

2736

best so far

2736

Variables
VariableValue
num2736
DepthFunction Call
Stack empty
0/6