Skip to main content
Back to problems
#1432
Medium Algorithms

Max difference you can get from changing an integer

Math Greedy
48.8% acceptance
Feb 25, 2026
595
377
You are given an integer num. You will apply the following steps to num two separate times: Pick a digit x (0 <= x <= 9). Pick another digit y (0 <= y <= 9). Note y can be equal to x. Replace all the occurrences of x in the decimal representation of num by y. Let a and b be the two results from applying the operation to num independently. Return the max difference between a and b. Note that neither a nor b may have any leading zeros, and must not be 0.

Solution

Rust
Time O(n)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn max_diff(num: i32) -> i32 {
    let s = num.to_string();
    let chars: Vec<char> = s.chars().collect();
    // Maximize: replace first non-9 digit with 9
    let a: i32 = if let Some(&d) = chars.iter().find(|&&c| c != '9') {
      s.replace(d, "9").parse().unwrap()
    } else { num };
    // Minimize: no leading zeros, not zero
    let b: i32 = if chars[0] != '1' {
      s.replace(chars[0], "1").parse().unwrap()
    } else if let Some(&d) = chars[1..].iter().find(|&&c| c != '0' && c != '1') {
      s.replace(d, "0").parse().unwrap()
    } else { num };
    a - b
  }
}