My solution just involved transforming num into a string twice:
- once for the
maxNum - once for the
minNum
and then I just determine what number I should be swapping while iterating through the digits
before swapping out the respective digits with 9 (for maxNum) and 0 (for minNum).
Finally, I can just return the difference between maxNum and minNum.
code
class Solution {
public:
int minMaxDifference(int num) {
string maxNum = to_string(num);
string minNum = to_string(num);
char numToChangeForMax = 'a';
char numToChangeForMin = minNum[0];
int i = 0;
for (; i < maxNum.size() && numToChangeForMax == 'a'; ++i) {
if (maxNum[i] != '9') {
numToChangeForMax = maxNum[i];
maxNum[i] = '9';
}
if (minNum[i] == numToChangeForMin) {
minNum[i] = '0';
}
}
for (; i < maxNum.size(); ++i) {
if (maxNum[i] == numToChangeForMax) {
maxNum[i] = '9';
}
if (minNum[i] == numToChangeForMin) {
minNum[i] = '0';
}
}
return stoi(maxNum) - stoi(minNum);
}
};
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
- 8 minutes and 32 seconds (oops)