[LeetCode] Maximum Difference by Remapping a Digit

2566. Maximum Difference by Remapping a Digit

You are given an integer num. You know that Danny Mittal will sneakily remap one of the 10 possible digits (0 to 9) to another digit.

Return the difference between the maximum and minimum values Danny can make by remapping exactly one digit in num.

Notes:

  • When Danny remaps a digit d1 to another digit d2, Danny replaces all occurrences of d1 in num with d2.
  • Danny can remap a digit to itself, in which case num does not change.
  • Danny can remap different digits for obtaining minimum and maximum values respectively.
  • The resulting number after remapping can contain leading zeroes.
  • We mentioned “Danny Mittal” to congratulate him on being in the top 10 in Weekly Contest 326.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
int modify(int n, int a, int b) {
string s = to_string(n);
for(int i = 0; i < s.length(); i++) {
if(s[i] - '0' == a) {
s[i] = '0' + b;
}
}
return stoi(s);
}
public:
int minMaxDifference(int num) {
vector<int> A;
for(int i = 0; i <= 9; i++) {
for(int j = 0; j <= 9; j++) {
A.push_back(modify(num,i,j));
}
}
sort(begin(A),end(A));
return A.back() - A.front();
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2023/02/19/PS/LeetCode/maximum-difference-by-remapping-a-digit/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.