1432. Max Difference You Can Get From Changing an Integer #1810
-
Topics: You are given an integer
Let Return the max difference between Note that neither Example 1:
Example 2:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We need to find the maximum possible difference between two numbers derived from the given integer Approach
Let's implement this solution in PHP: 1432. Max Difference You Can Get From Changing an Integer <?php
/**
* @param Integer $num
* @return Integer
*/
function maxDiff($num) {
$s = (string)$num;
$len = strlen($s);
$set = array();
for ($x = 0; $x < 10; $x++) {
$x_str = (string)$x;
for ($y = 0; $y < 10; $y++) {
$y_str = (string)$y;
$candidate = '';
for ($i = 0; $i < $len; $i++) {
if ($s[$i] === $x_str) {
$candidate .= $y_str;
} else {
$candidate .= $s[$i];
}
}
if (strlen($candidate) > 1 && $candidate[0] === '0') {
continue;
}
if ($candidate === "0") {
continue;
}
$num_val = intval($candidate);
$set[$num_val] = true;
}
}
if (count($set) == 0) {
return 0;
}
$min_val = min(array_keys($set));
$max_val = max(array_keys($set));
return $max_val - $min_val;
}
// Example usage:
echo maxDiff(555); // Output: 888
echo "\n";
echo maxDiff(9); // Output: 8
?> Explanation:
This approach efficiently explores all possible valid transformations of the input number, ensuring the solution meets the problem constraints and requirements. The use of a set ensures optimal storage and retrieval of unique valid numbers, and the final difference is straightforward to compute. |
Beta Was this translation helpful? Give feedback.
We need to find the maximum possible difference between two numbers derived from the given integer
num
by applying two separate operations. Each operation involves replacing all occurrences of a chosen digitx
with another digity
(which can be the same asx
). The resulting numbers must not have leading zeros and must not be zero.Approach
x
innum
with another digity
. The constraints are that the resulting number must not have leading zeros (unless it's a single zero, which is also invalid) and must not be zero.