-
Notifications
You must be signed in to change notification settings - Fork 0
/
maximum-swap.js
48 lines (38 loc) · 1016 Bytes
/
maximum-swap.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
/* Maximum Swap
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
*/
/**
* @param {number} num
* @return {number}
*/
var maximumSwap = function(num) {
num = (''+num).split('');
for(let i = 0; i < num.length; i++){
let currMax = num[i];
let indexSwap = -1;
for(let j = num.length - 1; j > i; j--){
if(currMax < num[j]){
currMax = num[j];
indexSwap = j;
}
}
if(indexSwap !== -1){
let temp = num[indexSwap];
num[indexSwap] = num[i];
num[i] = temp;
break;
}
}
return num.join('')
};