Skip to content

2566. Maximum Difference by Remapping a Digit 👍

  • Time: $O(1)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
class Solution {
 public:
  int minMaxDifference(int num) {
    const string s = to_string(num);
    const char to9 = s[firstNotNineIndex(s)];
    const char to0 = s[0];
    return getMax(s, to9) - getMin(s, to0);
  }

 private:
  int firstNotNineIndex(const string& s) {
    for (int i = 0; i < s.length(); ++i)
      if (s[i] != '9')
        return i;
    return 0;
  }

  int getMax(string s, char to9) {
    for (char& c : s)
      if (c == to9)
        c = '9';
    return stoi(s);
  }

  int getMin(string s, char to0) {
    for (char& c : s)
      if (c == to0)
        c = '0';
    return stoi(s);
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
class Solution {
  public int minMaxDifference(int num) {
    final String s = String.valueOf(num);
    final char to9 = s.charAt(firstNotNineIndex(s));
    final char to0 = s.charAt(0);
    return getMax(new StringBuilder(s), to9) - getMin(new StringBuilder(s), to0);
  }

  private int firstNotNineIndex(final String s) {
    for (int i = 0; i < s.length(); ++i)
      if (s.charAt(i) != '9')
        return i;
    return 0;
  }

  private int getMax(StringBuilder sb, char to9) {
    for (int i = 0; i < sb.length(); ++i)
      if (sb.charAt(i) == to9)
        sb.setCharAt(i, '9');
    return Integer.parseInt(sb.toString());
  }

  private int getMin(StringBuilder sb, char to0) {
    for (int i = 0; i < sb.length(); ++i)
      if (sb.charAt(i) == to0)
        sb.setCharAt(i, '0');
    return Integer.parseInt(sb.toString());
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class Solution:
  def minMaxDifference(self, num: int) -> int:
    s = str(num)
    to9 = s[self._firstNotNineIndex(s)]
    to0 = s[0]
    return int(s.replace(to9, '9')) - int(s.replace(to0, '0'))

  def _firstNotNineIndex(self, s: str) -> int:
    for i, c in enumerate(s):
      if c != '9':
        return i
    return 0