## 670. Maximum Swap

Given a non-negative integer, you could swap two digits at most once to get the maximum valued number. Return the maximum valued number you could get.

Example 1:

Input: 2736
Output: 7236
Explanation: Swap the number 2 and the number 7.


Example 2:

Input: 9973
Output: 9973
Explanation: No swap.


Note:

1. The given number is in the range [0, 108]

b'
\n\n

## Solution

\n
\n

#### Approach #1: Brute Force [Accepted]

\n

Intuition

\n

The number only has at most 8 digits, so there are only = 28 available swaps. We can easily brute force them all.

\n

Algorithm

\n

We will store the candidates as lists of length . For each candidate swap with positions , we swap the number and record if the candidate is larger than the current answer, then swap back to restore the original number.

\n

The only detail is possibly to check that we didn\'t introduce a leading zero. We don\'t actually need to check it, because our original number doesn\'t have one.

\n\n

Complexity Analysis

\n
\n
• \n

Time Complexity: , where is the total number of digits in the input number. For each pair of digits, we spend up to time to compare the final sequences.

\n
• \n
• \n

Space Complexity: , the information stored in .

\n
• \n
\n
\n

#### Approach #2: Greedy [Accepted]

\n

Intuition

\n

At each digit of the input number in order, if there is a larger digit that occurs later, we know that the best swap must occur with the digit we are currently considering.

\n

Algorithm

\n

We will compute , the index of the last occurrence of digit (if it exists).

\n

Afterwards, when scanning the number from left to right, if there is a larger digit in the future, we will swap it with the largest such digit; if there are multiple such digits, we will swap it with the one that occurs the latest.

\n\n

Complexity Analysis

\n
\n
• \n

Time Complexity: , where is the total number of digits in the input number. Every digit is considered at most once.

\n
• \n
• \n

Space Complexity: . The additional space used by only has up to 10 values.

\n
• \n
\n
\n

Analysis written by: @awice

\n
'