Input: num =11891Output: 99009Explanation:
To achieve the maximum value, Bob can remap the digit 1 to the digit 9 to yield 99899.To achieve the minimum value, Bob can remap the digit 1 to the digit 0, yielding 890.The difference between these two numbers is99009.
Input: num =90Output: 99Explanation:
The maximum value that can be returned by the functionis99(if0is replaced by 9) and the minimum value that can be returned by the functionis0(if9is replaced by 0).Thus, we return99.
To maximize the difference, remap a digit in num to 9 for the maximum value and to 0 for the minimum value. Try all possible digit remappings and pick the best results. Since only one digit can be remapped at a time (all its occurrences), brute-force all digit-to-digit remaps for both max and min.
classSolution {
public:int minMaxDifference(int num) {
string s = to_string(num);
int mx = num, mn = num;
for (char d ='0'; d <='9'; ++d) {
string t = s;
for (char&c : t) if (c == d) c ='9';
mx = max(mx, stoi(t));
}
for (char d ='0'; d <='9'; ++d) {
string t = s;
for (char&c : t) if (c == d) c ='0';
mn = min(mn, stoi(t));
}
return mx - mn;
}
};
classSolution {
publicintminMaxDifference(int num) {
String s = Integer.toString(num);
int mx = num, mn = num;
for (char d ='0'; d <='9'; d++) {
String t = s.replace(d, '9');
mx = Math.max(mx, Integer.parseInt(t));
}
for (char d ='0'; d <='9'; d++) {
String t = s.replace(d, '0');
mn = Math.min(mn, Integer.parseInt(t));
}
return mx - mn;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
classSolution {
funminMaxDifference(num: Int): Int {
val s = num.toString()
var mx = num
var mn = num
for (d in'0'..'9') {
val t = s.replace(d, '9')
mx = maxOf(mx, t.toInt())
}
for (d in'0'..'9') {
val t = s.replace(d, '0')
mn = minOf(mn, t.toInt())
}
return mx - mn
}
}
1
2
3
4
5
6
7
8
9
10
11
12
classSolution:
defminMaxDifference(self, num: int) -> int:
s = str(num)
mx = num
mn = num
for d in'0123456789':
t = s.replace(d, '9')
mx = max(mx, int(t))
for d in'0123456789':
t = s.replace(d, '0')
mn = min(mn, int(t))
return mx - mn
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
impl Solution {
pubfnmin_max_difference(num: i32) -> i32 {
let s = num.to_string();
letmut mx = num;
letmut mn = num;
for d inb'0'..=b'9' {
let t: String = s.bytes().map(|c|if c == d { b'9' } else { c }).map(|c| c aschar).collect();
let v = t.parse::<i32>().unwrap();
if v > mx { mx = v; }
}
for d inb'0'..=b'9' {
let t: String = s.bytes().map(|c|if c == d { b'0' } else { c }).map(|c| c aschar).collect();
let v = t.parse::<i32>().unwrap();
if v < mn { mn = v; }
}
mx - mn
}
}