Hey Devs! 👋
Let’s break down a fun greedy + string manipulation problem — 2566: Maximum Difference by Remapping a Digit. This one is perfect for sharpening your skills in character replacement and greedy thinking.
📝 Problem Statement
Given a number num
, Bob is allowed to remap exactly one digit (0–9) to any other digit (including itself). All occurrences of the selected digit are changed.
Your job:
Return the maximum difference between the largest and smallest number Bob can create by remapping one digit.
✅ Leading zeroes are allowed after remapping.
🧩 Example
Input: num = 11891
Output: 99009
Explanation:
- For maximum value: Replace
'1' → '9'
→ becomes99899
- For minimum value: Replace
'1' → '0'
→ becomes890
- Difference =
99899 - 890 = 99009
💡 Strategy & Intuition
To get:
-
Maximum value: Change the first non-'9' digit to
'9'
-
Minimum value: Change the first digit to
'0'
Why?
- Changing leftmost significant digits impacts the number most.
- Changing the same digit in all its occurrences ensures a larger shift.
⚙️ C++ Implementation
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);
}
};
🌐 JavaScript Version
var minMaxDifference = function(num) {
let s = num.toString();
const to9 = [...s].find(c => c !== '9') || s[0];
const to0 = s[0];
const getMax = s => parseInt(s.replaceAll(to9, '9'));
const getMin = s => parseInt(s.replaceAll(to0, '0'));
return getMax(s) - getMin(s);
};
🐍 Python Version
def minMaxDifference(num: int) -> int:
s = str(num)
to9 = next((c for c in s if c != '9'), s[0])
to0 = s[0]
max_val = int(s.replace(to9, '9'))
min_val = int(s.replace(to0, '0'))
return max_val - min_val
🧪 Test Cases
Input: num = 11891
Output: 99009
Input: num = 90
Output: 99
Input: num = 999
Output: 999 - 0 = 999
Input: num = 1000
Output: 9000 - 0 = 9000
⏱️ Time & Space Complexity
Time Complexity: O(n) — One pass for replacement (n = number of digits)
Space Complexity: O(1) — Only a few variables used
✅ Conclusion
This problem is an excellent exercise in greedy digit manipulation and reinforces string traversal techniques.
Remember:
- Maximize by turning first non-9 into 9
- Minimize by turning first digit into 0
Drop a ❤️ if this helped, and stay tuned for more bitesize breakdowns!
Happy coding, folks! 🚀
Top comments (6)
Good Explanation
thanks anna
Honestly love how this is laid out makes me wanna go solve a few myself
Glad you liked it sir ❤️
Super clean breakdown..
Some comments may only be visible to logged-in visitors. Sign in to view all comments.