A Fun String Manipulation + Greedy Problem
Hey Devs! π
Letβs decode another cool number-manipulation problem today: 1432. Max Difference You Can Get From Changing an Integer.
This one is about finding the maximum possible difference by replacing digits β twice, independently!
π Problem Summary
You're given an integer num
. You perform this operation twice:
- Choose a digit
x
and replace all occurrences of it with another digity
(0β9, can be the same). - Do this twice independently to form two new numbers
a
andb
.
Your task:
Return the maximum difference between a
and b
.
π« No leading zeroes allowed
π« Final numbers must not be 0
π§© Example
Input: num = 555
Output: 888
Explanation:
- For maximum number: Replace
5 β 9
β999
- For minimum number: Replace
5 β 1
β111
- Difference:
999 - 111 = 888
π‘ Intuition & Strategy
To get:
-
Maximum value: Replace the first non-9 digit with
9
-
Minimum value:
- If the first digit isnβt
1
, replace it with1
- Else, find another digit (not the first) to replace with
0
- If the first digit isnβt
We need to avoid leading zeroes, so we're careful not to start b
with 0
.
βοΈ C++ Implementation
class Solution {
public:
int maxDiff(int num) {
string t = to_string(num); // for max
string p = to_string(num); // for min
char c;
// For max: Replace first non-9 digit with '9'
for (char ch : t) {
if (ch != '9') {
c = ch;
break;
}
}
for (char& ch : t)
if (ch == c)
ch = '9';
// For min:
bool changed = false;
char first = p[0];
if (first != '1') {
for (char& ch : p) {
if (ch == first)
ch = '1';
}
} else {
for (int i = 1; i < p.size(); ++i) {
if (p[i] != '0' && p[i] != first) {
char c3 = p[i];
for (int j = 1; j < p.size(); ++j)
if (p[j] == c3)
p[j] = '0';
break;
}
}
}
return stoi(t) - stoi(p);
}
};
π JavaScript Version
var maxDiff = function(num) {
const s = num.toString().split('');
// Get max
let maxS = [...s];
let replaceDigit = maxS.find(d => d !== '9');
maxS = maxS.map(d => d === replaceDigit ? '9' : d);
// Get min
let minS = [...s];
if (minS[0] !== '1') {
minS = minS.map(d => d === minS[0] ? '1' : d);
} else {
for (let i = 1; i < minS.length; i++) {
if (minS[i] !== '0' && minS[i] !== minS[0]) {
let target = minS[i];
minS = minS.map((d, idx) => (d === target && idx !== 0 ? '0' : d));
break;
}
}
}
return parseInt(maxS.join('')) - parseInt(minS.join(''));
};
π Python Version
def maxDiff(num: int) -> int:
s = list(str(num))
# Max version
for d in s:
if d != '9':
max_s = [c if c != d else '9' for c in s]
break
else:
max_s = s[:]
# Min version
if s[0] != '1':
min_s = [c if c != s[0] else '1' for c in s]
else:
min_s = s[:]
for i in range(1, len(s)):
if s[i] != '0' and s[i] != s[0]:
target = s[i]
min_s = [c if i == 0 or c != target else '0' for i, c in enumerate(s)]
break
return int("".join(max_s)) - int("".join(min_s))
π§ͺ Test Cases
Input: num = 555
Output: 888 // 999 - 111
Input: num = 9
Output: 8 // 9 - 1
Input: num = 1009
Output: 9009 // 9999 - 99
Input: num = 123456
Output: 820000 // 923456 - 103456
β±οΈ Time & Space Complexity
Time: O(n) β where n is the number of digits
Space: O(n) β due to new strings created
β Final Thoughts
This problem trains your skills in:
- Greedy digit replacement
- Handling leading zeroes
- Working with strings instead of raw numbers
π Tip: When dealing with number digit changes, converting to string
gives you total control!
If you liked this breakdown, leave a β€οΈ and follow for more practical algorithm guides!
Happy coding! π οΈ
Top comments (2)
Good
Thanks Anna
Some comments may only be visible to logged-in visitors. Sign in to view all comments.