Skip to main content
Back to problems
#2566
Easy Algorithms

Maximum difference by remapping a digit

Math Greedy
76.1% acceptance
Feb 25, 2026
608
75
You are given an integer num. You know that Bob will sneakily remap one of the 10 possible digits (0 to 9) to another digit. Return the difference between the maximum and minimum values Bob can make by remapping exactly one digit in num. Notes: When Bob remaps a digit d1 to another digit d2, Bob replaces all occurrences of d1 in num with d2. Bob can remap a digit to itself, in which case num does not change. Bob can remap different digits for obtaining minimum and maximum values respectively. The resulting number after remapping can contain leading zeroes.

Solution

Rust
Time O(n)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn min_max_difference(num: i32) -> i32 {
    let s = num.to_string();
    // Max: replace first digit that is not '9' with '9'
    let max_val = if let Some(d) = s.chars().find(|&c| c != '9') {
      s.replace(d, "9").parse::<i64>().unwrap()
    } else {
      num as i64
    };
    // Min: replace all occurrences of the first digit with '0'
    let first_digit = s.chars().next().unwrap();
    let min_val = s.replace(first_digit, "0").parse::<i64>().unwrap_or(0);
    (max_val - min_val) as i32
  }
}