Maximum Swap
Description
Given a non-negative integer, you could swap two digits at most once to get the maximum valued number. Return the maximum valued number you could get.
Example 1:
Example 2:
Note:
The given number is in the range [0, ]
Solutions
My solution
Algorithm:
Let
num[i]
denote the digit.Set
i = 0
.While
num[i]
is larger than any digit after it,++i
.Find the largest digit after
num[i]
, saynum[j]
(if there are multiple largest digits, use the last one). Then swapnum[i]
andnum[j]
.
A better solution
Same idea, but better implementation. The key is to store only the last occurrence of .
Credit: Java simple solution, O(n) time
Last updated