Skip to main content
Back to problems
#670
Medium Algorithms

Maximum swap

Math Greedy
51.9% acceptance
Feb 20, 2026
4280
274
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.

Solution

Rust
Time O(n²)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn maximum_swap(num: i32) -> i32 {
    let mut digits: Vec<u8> = num.to_string().bytes().map(|b| b - b'0').collect();
    let n = digits.len();
    // last[d] = last index of digit d
    let mut last = [0usize; 10];
    for i in 0..n {
      last[digits[i] as usize] = i;
    }
    for i in 0..n {
      for d in (digits[i] as usize + 1..=9).rev() {
        if last[d] > i {
          digits.swap(i, last[d]);
          return digits.iter().fold(0i32, |acc, &x| acc * 10 + x as i32);
        }
      }
    }
    num
  }
}