This problem is just yesterdays problem but with more test cases to check for.
This solution is just yesterdays solution
but with an extra test-case;
since to find the max difference, both numbers cannot have a leading 0,
it implies that to find the minimum value, we either have to:
- if the first digit is not
1
- then we can convert all instances of that digit to
1- else, the first digit is
1and we iterate through the string to find the first instance of a digit that is NOT1or0
- then we can convert all instances of that digit to
0
code
class Solution {
public:
int maxDiff(int num) {
string maxAns = to_string(num);
string minAns = to_string(num);
int i = 0;
char maxTemp = '-';
char minTemp = '-';
char toReplace;
for (; i < maxAns.size() && (maxTemp == '-' || minTemp == '-'); ++i) {
if (maxTemp == '-' && maxAns[i] != '9') {
maxTemp = maxAns[i];
maxAns[i] = '9';
} else if (maxTemp == maxAns[i]) {
maxAns[i] = '9';
}
if (minTemp == '-' && i == 0 && minAns[i] != '1') {
minTemp = minAns[i];
toReplace = '1';
minAns[i] = toReplace;
} else if (minTemp == '-' && minAns[i] != '1' && minAns[i] != '0') {
minTemp = minAns[i];
toReplace = '0';
minAns[i] = toReplace;
} else if (minTemp == minAns[i]) {
minAns[i] = toReplace;
}
}
for (; i < maxAns.size(); ++i) {
if (maxTemp == maxAns[i]) {
maxAns[i] = '9';
}
if (minTemp == minAns[i]) {
minAns[i] = toReplace;
}
}
return stoi(maxAns) - stoi(minAns);
}
};
complexity
- Time:
O(log(n))wherenisnum- Space:
O(log(n))
learnings
- you can do it with
O(1)space complexity by using math
time taken
- 5 minutes and 56 seconds