Maximum Swap
Make a number as large as possible by swapping two of its digits at most once.
Given a non-negative integer num
Example 1
Output: 7236
Explanation: swap 2 and 7.
Example 2
Output: 9973
Explanation: no swap helps.
Example 3
Output: 9913
Explanation: swap the 1 with the last 9, not the first.
The Idea
Write 2736 on four cards, one digit per card. You may trade the places of two cards once. Which trade gives the biggest number? The leftmost card counts most: the 2 is worth 2000, while the 7 next to it is worth only 700. Putting the 7 in front gives 7236, and no other trade beats it.
So the swap should raise the leftmost digit that can be raised. In 9973 no digit has a bigger one after it, because the digits already go down from left to right, and that is why no swap helps. In 2736 the very first digit, 2, can grow, so that is where the swap goes.
Example 3, 1993, raises one more question. The 1 in front can grow, and the biggest digit after it is 9. But there are two 9s, at position 1 and position 2, counting positions from 0 on the left. Which one should move to the front?
Look at the picture below. Swapping the 1 with the first 9 gives 9193, and swapping it with the last 9 gives 9913. Both put a 9 in front, so the difference is where the 1 lands. With the last 9, the 1 goes as far right as it can, where a small digit costs the least.
The table on the right, headed "last position of each digit", is how we find that 9 quickly. Read 1993 from left to right and write down each digit's position as you meet it. The 9 is seen at position 1, then at position 2, and the later position 2 is the one kept.
So the whole answer is one choice: the leftmost digit that has a bigger digit somewhere after it, swapped with the last copy of the biggest such digit. Settling the most important digit first and never coming back to it is called a greedy choice, and here it is safe, because nothing to the right can make up for a smaller digit further left.
Solution Approach
Turning that idea into code means settling three things: which position to change, which digit to bring there, and how to find that digit's last position fast, after a look at the simple way of trying every swap.
Trying every swap
Why not try every pair of positions, build each new number and keep the largest? For 1993 there are only six pairs, so this is a fine first program. But every pair builds a whole new number, so the work grows with the cube of the digit count. It also never says why a swap wins, while the rule from the idea goes straight to the right swap.
Which position to change
Where does the swap go? Walk the digits from the left and stop at the first position that has a bigger digit somewhere after it. Every digit before that position is already at least as big as all the digits after it, so no swap can raise it. If the walk finds no such position, as in 9973, the number is returned as it is.
Which digit to bring in
Which bigger digit should come in? The biggest one that appears later, because it raises the changed position the most. Digits only go from 0 to 9, so we can simply try 9, then 8, and so on, down to one more than the current digit. The first value that appears after the position wins.
Finding the last copy quickly
How do we know whether a value appears later, and where its last copy is? Before the walk, one pass over the digits fills an array of ten cells, one per digit value, with each value's last position. A value appears after the position being changed exactly when its last position is greater, and that same cell says which copy to swap with.
Java Solution
The method maximumSwap
- First, turn the number into an array of characters with
and call itInteger.toString(num).toCharArray() , so each digit can be read and swapped by its position.digits - Create
, anlast array of 10 cells, one per digit value. A loop overint from left to right stores each position in the cell of its digit, so a later copy overwrites an earlier one. For 1993,digits ends up as 2.last[9] - A second loop moves
over the positions from the left. Inside it, an inner loop countsi down from 9 to one more than the digit atd , trying the bigger values, largest first.i - When
, the valuelast[d] > i appears after positiond . Swapi withdigits[i] , turn the characters back into a number withdigits[last[d]] and return it.Integer.parseInt - If the loops finish without a swap, no digit has a bigger one after it, so return
unchanged.num
The numintInteger.parseInt
The main
public class MaximumSwap {
public static int maximumSwap(int num) {
char[] digits = Integer.toString(num).toCharArray();
int[] last = new int[10]; // last[d]: last position of digit d
for (int i = 0; i < digits.length; i++) {
last[digits[i] - '0'] = i;
}
for (int i = 0; i < digits.length; i++) {
for (int d = 9; d > digits[i] - '0'; d--) { // bigger digits, largest first
if (last[d] > i) { // does d appear after position i?
char t = digits[i];
digits[i] = digits[last[d]];
digits[last[d]] = t;
return Integer.parseInt(new String(digits));
}
}
}
return num; // no swap makes it bigger
}
public static void main(String[] args) {
int[] tests = {2736, 9973, 1993, 0, 7, 98368, 1001};
for (int num : tests) {
System.out.println(num + " -> " + maximumSwap(num));
}
}
}
Running it prints:
2736 -> 7236
9973 -> 9973
1993 -> 9913
0 -> 0
7 -> 7
98368 -> 98863
1001 -> 1100
Look at 1993 -> 9913last[9]
The line 98368 -> 98863
The last line, 1001 -> 1100
Complexity
The method reads the digits once to fill last
- Time: O(n), because the first loop visits each of the n digits once, and the walk tries at most nine bigger values at each position before it swaps or moves on.
- Space: O(n), because
and the string built from it hold all n digits, whiledigits always has ten cells, whatever the number.last
Making the leftmost digits as good as possible is also the rule in