You are given an integer num. You can swap two digits at most once to get the maximum valued number.
Return the maximum valued number you can get.
Example 1:
Input: num = 2736
Output: 7236
Explanation: Swap the number 2 and the number 7.
Example 2:
Input: num = 9973
Output: 9973
Explanation: No swap.
Constraints:
0 <= num <= 108
Solutions
Solution 1: Greedy Algorithm
Thinking
Swap at most two digits to maximize the number. Trying every pair is unnecessary.
From the right, record the index of the largest digit to the right (inclusive). From the left, swap at the first \(s[i]<s[d[i]]\). That raises the highest possible place.
First, we convert the number into a string \(s\). Then, we traverse the string \(s\) from right to left, using an array or hash table \(d\) to record the position of the maximum number to the right of each number (it can be the position of the number itself).
Next, we traverse \(d\) from left to right. If \(s[i] < s[d[i]]\), we swap them and exit the traversal process.
Finally, we convert the string \(s\) back into a number, which is the answer.
The time complexity is \(O(\log M)\), and the space complexity is \(O(\log M)\). Here, \(M\) is the range of the number \(num\).
Method 1 stores a right-max index array. One right-to-left scan can keep the best seen digit and the leftmost profitable swap, without the extra array.