Sponsored
Sponsored
The idea is to always try and bring the largest possible digit to the leftmost position if it maximizes the number. For this, we can use a map to record the last occurrence of each digit. By iterating through the number, we can then attempt swapping if any larger digit occurs later.
Time Complexity: O(n), where n is the number of digits in num.
Space Complexity: O(1) as the storage is constant due to limited digit size.
1function maximumSwap(num) {
2 let digits = Array.from(String(num), Number);
3 let last = Array(10).fill(0);
4
5 for (let i = 0; i < digits.length; i++) {
6 last[digits[i]] = i;
7 }
8
9 for (let i = 0; i < digits.length; i++) {
10 for (let d = 9; d > digits[i]; d--) {
11 if (last[d] > i) {
12 [digits[i], digits[last[d]]] = [digits[last[d]], digits[i]];
13 return parseInt(digits.join(''));
14 }
15 }
16 }
17 return num;
18}
19
20let num = 2736;
21console.log(maximumSwap(num));
For JavaScript, we utilize array manipulation techniques to achieve the desired swap by tracking last occurrences of each digit and making the appropriate swap to maximize the number.