2566. Maximum Difference by Remapping a Digit #1806
-
Topics: You are given an integer Return the difference between the maximum and minimum values Bob can make by remapping exactly one digit in Notes:
Example 1:
Example 2:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We need to determine the difference between the maximum and minimum values Bob can obtain by remapping exactly one digit in the given integer Approach
Let's implement this solution in PHP: 2566. Maximum Difference by Remapping a Digit <?php
/**
* @param Integer $num
* @return Integer
*/
function minMaxDifference($num) {
$s = (string)$num;
$n = strlen($s);
$max_str = $s;
for ($i = 0; $i < $n; $i++) {
if ($s[$i] != '9') {
$d = $s[$i];
$max_str = str_replace($d, '9', $s);
break;
}
}
$d0 = $s[0];
$min_str = str_replace($d0, '0', $s);
$max_val = (int)$max_str;
$min_val = (int)$min_str;
return $max_val - $min_val;
}
// Example test cases
echo minMaxDifference(11891) . "\n"; // Output: 99009
echo minMaxDifference(90) . "\n"; // Output: 99
?> Explanation:
This approach efficiently computes the desired difference by leveraging simple string manipulation and arithmetic operations, ensuring optimal performance even for large numbers. |
Beta Was this translation helpful? Give feedback.
We need to determine the difference between the maximum and minimum values Bob can obtain by remapping exactly one digit in the given integer
num
. The remapping involves replacing all occurrences of a chosen digit with another digit. The solution involves two main steps: finding the maximum possible value after remapping and finding the minimum possible value after remapping, then computing their difference.Approach