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.
Input: 2736 Output: 7236 Explanation: Swap the number 2 and the number 7.
Input: 9973 Output: 9973 Explanation: No swap.
- The given number is in the range [0, 108]
impl Solution {
pub fn maximum_swap(num: i32) -> i32 {
let mut digits = num.to_string().into_bytes();
let mut last = [0; 10];
for i in 0..digits.len() {
last[(digits[i] - b'0') as usize] = i;
}
for i in 0..digits.len() {
for j in (((digits[i] - b'0') as usize + 1)..=9).rev() {
if last[j] > i {
digits.swap(i, last[j]);
return String::from_utf8(digits).unwrap().parse().unwrap();
}
}
}
num
}
}