LeetCode 0670. Maximum Swap Solution in Java, Python, C++, JavaScript, Go & Rust | Explanation + Code

CoderIndeed
0
0670. Maximum Swap

Description

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

Solutions

Solution 1: Greedy Algorithm

First, we convert the number into a string s. Then, we traverse the string s from right to left, using an array or hash table d to record the position of the maximum number to the right of each number (it can be the position of the number itself).

Next, we traverse d from left to right. If s[i] < s[d[i]], we swap them and exit the traversal process.

Finally, we convert the string s back into a number, which is the answer.

The time complexity is O(log M), and the space complexity is O(log M). Here, M is the range of the number num.

PythonJavaC++GoTypeScriptRust
class Solution: def maximumSwap(self, num: int) -> int: s = list(str(num)) n = len(s) d = list(range(n)) for i in range(n - 2, -1, -1): if s[i] <= s[d[i + 1]]: d[i] = d[i + 1] for i, j in enumerate(d): if s[i] < s[j]: s[i], s[j] = s[j], s[i] break return int(''.join(s))(code-box)

Solution 2: Space Optimized Greedy

TypeScriptJavaScript
function maximumSwap(num: number): number { const ans = [...String(num)]; let [min, max, maybeMax, n] = [-1, -1, -1, ans.length]; for (let i = n - 1; i >= 0; i--) { if (ans[i] > (ans[maybeMax] ?? -1)) maybeMax = i; if (i < maybeMax && ans[i] < ans[maybeMax]) { [min, max] = [i, maybeMax]; } } if (~min && ~max && min < max) { [ans[min], ans[max]] = [ans[max], ans[min]]; } return +ans.join(''); }(code-box)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !