Max Difference You Can Get From Changing an Integer

medium math greedy

Problem

You're given an integer num. Twice, pick a digit x and a digit y (0–9) and replace every occurrence of x in num with y. The result must not have leading zero or be zero. Return the maximum possible difference between the two results.

Inputnum = 555
Output888
Max: replace 5 → 9 to get 999. Min: replace 5 → 1 to get 111. Diff = 888.

def max_diff(num):
    s = str(num)
    # max: find first digit != 9 and replace with 9
    a = s
    for c in s:
        if c != '9':
            a = s.replace(c, '9'); break
    # min: leading digit handled specially
    if s[0] != '1':
        b = s.replace(s[0], '1')
    else:
        b = s
        for c in s[1:]:
            if c not in ('0', '1'):
                b = s.replace(c, '0'); break
    return int(a) - int(b)
function maxDiff(num) {
  const s = String(num);
  let a = s;
  for (const c of s) {
    if (c !== '9') { a = s.split(c).join('9'); break; }
  }
  let b = s;
  if (s[0] !== '1') {
    b = s.split(s[0]).join('1');
  } else {
    for (let i = 1; i < s.length; i++) {
      if (s[i] !== '0' && s[i] !== '1') { b = s.split(s[i]).join('0'); break; }
    }
  }
  return parseInt(a, 10) - parseInt(b, 10);
}
class Solution {
    public int maxDiff(int num) {
        String s = String.valueOf(num);
        String a = s;
        for (char c : s.toCharArray()) {
            if (c != '9') { a = s.replace(c, '9'); break; }
        }
        String b = s;
        if (s.charAt(0) != '1') {
            b = s.replace(s.charAt(0), '1');
        } else {
            for (int i = 1; i < s.length(); i++) {
                char c = s.charAt(i);
                if (c != '0' && c != '1') { b = s.replace(c, '0'); break; }
            }
        }
        return Integer.parseInt(a) - Integer.parseInt(b);
    }
}
int maxDiff(int num) {
    string s = to_string(num);
    string a = s;
    for (char c : s) {
        if (c != '9') { replace(a.begin(), a.end(), c, '9'); break; }
    }
    string b = s;
    if (s[0] != '1') {
        replace(b.begin(), b.end(), s[0], '1');
    } else {
        for (int i = 1; i < (int)s.size(); i++) {
            if (s[i] != '0' && s[i] != '1') { replace(b.begin(), b.end(), s[i], '0'); break; }
        }
    }
    return stoi(a) - stoi(b);
}
Time: O(d) Space: O(d)