Problem Description
Explanation:
To solve this problem, we need to find the maximum difference we can get by changing an integer num
twice following the given rules. We will iterate through the digits of num
and for each digit, we will try to find the maximum and minimum possible numbers after changing that digit. Finally, we calculate the maximum difference between these two numbers.
-
Algorithm:
- Initialize
maxDiff
to -1. - Convert
num
to a string for easier manipulation. - Iterate over each digit in the string representation of
num
.- For each digit, try replacing it with all possible digits from 1 to 9 (excluding the current digit) and find the maximum and minimum numbers that can be formed.
- Update
maxDiff
with the maximum difference found so far.
- Return
maxDiff
.
- Initialize
-
Time Complexity: O(N) where N is the number of digits in
num
. -
Space Complexity: O(N) for storing the string representation of
num
.
:
Solutions
class Solution {
public int maxDiff(int num) {
String numStr = String.valueOf(num);
int maxDiff = -1;
for (int i = 0; i < numStr.length(); i++) {
char c = numStr.charAt(i);
for (char replace = '0'; replace <= '9'; replace++) {
String newNum = numStr.replace(c, replace);
if (newNum.charAt(0) != '0') {
int newInt = Integer.parseInt(newNum);
maxDiff = Math.max(maxDiff, newInt - num);
}
}
}
return maxDiff;
}
}
Loading editor...