Skip to content

Commit 61dbcf3

Browse files
authored
Create 670-maximum-swap.js
1 parent 9c9a5e0 commit 61dbcf3

File tree

1 file changed

+18
-0
lines changed

1 file changed

+18
-0
lines changed

670-maximum-swap.js

+18
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
/**
2+
* @param {number} num
3+
* @return {number}
4+
*/
5+
const maximumSwap = function(num) {
6+
const arr = ('' + num).split('')
7+
for(let i = 0; i < arr.length - 1; i++) {
8+
let cur = +arr[i]
9+
let nextMax = Math.max(...arr.slice(i+1).map(el => +el))
10+
if (nextMax > cur) {
11+
let idx = arr.lastIndexOf(''+nextMax)
12+
arr[i] = nextMax
13+
arr[idx] = cur
14+
break
15+
}
16+
}
17+
return +(arr.join(''))
18+
};

0 commit comments

Comments
 (0)