2566. Maximum Difference by Remapping a Digit
EasyView on LeetCode
Time: O(d)
Space: O(d)
Advertisement
Intuition
Maximum difference by changing one digit. To maximize: increase leftmost non-9 digit to 9. Decrease: if first digit > 1 set to 1, else find first non-0/1 and set to 0.
Algorithm
- 1Max: replace first non-9 digit with 9.
- 2Min: if first digit != 1: replace all first-digit with 1. Else: replace first non-0/1 with 0.
Common Pitfalls
- •Min must not create leading zeros. Special case for first digit.
2566.cs
C#
// Approach: Max: replace first digit with 9; Min: replace first non-9 digit with 0 (or 1st digit→0).
// Time: O(d) Space: O(d)
public class Solution
{
public int MinMaxDifference(int num)
{
string numStr = num.ToString(); // Convert the integer to a string for manipulation
int minVal = int.Parse(numStr.Replace(numStr[0], '0')); // Replace first digit with '0' to get the minimum value
// Iterate over the characters in the string
foreach (char digit in numStr)
{
if (digit != '9')
// Replace the current digit with '9' to get the maximum value and return the difference
return int.Parse(numStr.Replace(digit, '9')) - minVal;
}
// If all digits are '9', return the difference between the original number and minVal
return num - minVal;
}
}Advertisement
Was this solution helpful?