2566. Maximum Difference by Remapping a Digit
Explanation:
To solve this problem, we need to consider all possible digit remappings and calculate the maximum and minimum values that can be obtained by remapping a single digit. We will iterate through all digits from 0 to 9, and for each digit, we will calculate the maximum and minimum values that can be obtained by remapping that digit to another digit. Finally, we will return the maximum difference between the maximum and minimum values.
Algorithmic Idea:
- Iterate through all digits from 0 to 9.
- For each digit, calculate the maximum value by replacing all occurrences of that digit with 9 and the minimum value by replacing all occurrences of that digit with 0.
- Update the maximum difference if the difference between the maximum and minimum values is greater than the current maximum difference.
- Return the maximum difference.
Time Complexity:
- The time complexity of this solution is O(N), where N is the number of digits in the input number.
Space Complexity:
- The space complexity of this solution is O(1) as we are using constant extra space.
:
class Solution {
public int maxDiff(int num) {
String numStr = String.valueOf(num);
int maxDiff = 0;
for (char c = '0'; c <= '9'; c++) {
String replaceWith9 = numStr.replace(c, '9');
String replaceWith0 = numStr.replace(c, '0');
if (c != '0' && replaceWith0.charAt(0) != '0') {
int diff = Integer.parseInt(replaceWith9) - Integer.parseInt(replaceWith0);
maxDiff = Math.max(maxDiff, diff);
}
}
return maxDiff;
}
}
Code Editor (Testing phase)
Improve Your Solution
Use the editor below to refine the provided solution. Select a programming language and try the following:
- Add import statement if required.
- Optimize the code for better time or space complexity.
- Add test cases to validate edge cases and common scenarios.
- Handle error conditions or invalid inputs gracefully.
- Experiment with alternative approaches to deepen your understanding.
Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.