Skip to content

Commit 3669d7a

Browse files
committed
Add solution #670
1 parent a96686d commit 3669d7a

File tree

2 files changed

+32
-0
lines changed

2 files changed

+32
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -502,6 +502,7 @@
502502
664|[Strange Printer](./0664-strange-printer.js)|Hard|
503503
667|[Beautiful Arrangement II](./0667-beautiful-arrangement-ii.js)|Medium|
504504
668|[Kth Smallest Number in Multiplication Table](./0668-kth-smallest-number-in-multiplication-table.js)|Hard|
505+
670|[Maximum Swap](./0670-maximum-swap.js)|Medium|
505506
680|[Valid Palindrome II](./0680-valid-palindrome-ii.js)|Easy|
506507
684|[Redundant Connection](./0684-redundant-connection.js)|Medium|
507508
686|[Repeated String Match](./0686-repeated-string-match.js)|Easy|

solutions/0670-maximum-swap.js

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
/**
2+
* 670. Maximum Swap
3+
* https://leetcode.com/problems/maximum-swap/
4+
* Difficulty: Medium
5+
*
6+
* You are given an integer num. You can swap two digits at most once to get the maximum
7+
* valued number.
8+
*
9+
* Return the maximum valued number you can get.
10+
*/
11+
12+
/**
13+
* @param {number} num
14+
* @return {number}
15+
*/
16+
var maximumSwap = function(num) {
17+
const digits = [...(num).toString()];
18+
const last = new Array(10).fill(-1);
19+
digits.forEach((d, i) => last[d] = i);
20+
21+
for (let i = 0; i < digits.length; i++) {
22+
for (let d = 9; d > digits[i]; d--) {
23+
if (last[d] > i) {
24+
[digits[i], digits[last[d]]] = [digits[last[d]], digits[i]];
25+
return +digits.join('');
26+
}
27+
}
28+
}
29+
30+
return num;
31+
};

0 commit comments

Comments
 (0)