Skip to content

Latest commit

 

History

History
46 lines (38 loc) · 1.12 KB

File metadata and controls

46 lines (38 loc) · 1.12 KB

670. Maximum Swap

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:

Input: 2736
Output: 7236
Explanation: Swap the number 2 and the number 7.

Example 2:

Input: 9973
Output: 9973
Explanation: No swap.

Note:

  1. The given number is in the range [0, 108]

Solutions (Rust)

1. Greedy

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
    }
}