1323. Maximum 69 Number #2060
-
Topics: You are given a positive integer Return the maximum number you can get by changing at most one digit ( Example 1:
Example 2:
Example 3:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We need to find the maximum number achievable by changing at most one digit in a given positive integer composed only of digits '6' and '9'. The key observation here is that changing a '6' to '9' increases the number's value, while changing a '9' to '6' decreases it. Therefore, the optimal strategy is to change the leftmost '6' to '9' to maximize the increase in the number's value. If there are no '6's, the number is already at its maximum value. Approach
This approach efficiently finds the optimal digit to change in a single pass through the digits, leveraging the fact that changing the leftmost '6' yields the highest possible value. Let's implement this solution in PHP: 1323. Maximum 69 Number <?php
/**
* @param Integer $num
* @return Integer
*/
function maximum69Number ($num) {
$str = (string)$num;
$len = strlen($str);
for ($i = 0; $i < $len; $i++) {
if ($str[$i] == '6') {
$str[$i] = '9';
break;
}
}
return (int)$str;
}
// Test cases
echo maximum69Number(9669) . "\n"; // Output: 9969
echo maximum69Number(9996) . "\n"; // Output: 9999
echo maximum69Number(9999) . "\n"; // Output: 9999
?> Explanation:
This approach efficiently maximizes the number's value with minimal operations, leveraging a greedy strategy to prioritize the leftmost '6' for conversion. The time complexity is O(n), where n is the number of digits in |
Beta Was this translation helpful? Give feedback.
We need to find the maximum number achievable by changing at most one digit in a given positive integer composed only of digits '6' and '9'. The key observation here is that changing a '6' to '9' increases the number's value, while changing a '9' to '6' decreases it. Therefore, the optimal strategy is to change the leftmost '6' to '9' to maximize the increase in the number's value. If there are no '6's, the number is already at its maximum value.
Approach