670. Maximum Swap #711
Answered
by
kovatz
mah-shamim
asked this question in
Q&A
670. Maximum Swap
#711
-
Topics: You are given an integer Return the maximum valued number you can get. Example 1:
Example 2:
Constraints:
|
Beta Was this translation helpful? Give feedback.
Answered by
kovatz
Oct 17, 2024
Replies: 1 comment 2 replies
-
We can follow a greedy approach. Here's a step-by-step explanation and the solution: Approach:
Let's implement this solution in PHP: 670. Maximum Swap <?php
/**
* @param Integer $num
* @return Integer
*/
function maximumSwap($num) {
// Convert the number into an array of characters (digits)
$numStr = strval($num);
$numArr = str_split($numStr);
$n = count($numArr);
// Array to store the last occurrence of each digit (0-9)
$last = array_fill(0, 10, -1);
// Populate the last occurrence array
for ($i = 0; $i < $n; $i++) {
$last[$numArr[$i]] = $i;
}
// Traverse the digits to find the best place to swap
for ($i = 0; $i < $n; $i++) {
// Check for a larger digit that appears later
for ($d = 9; $d > $numArr[$i]; $d--) {
if ($last[$d] > $i) {
// Swap digits
$temp = $numArr[$i];
$numArr[$i] = $numArr[$last[$d]];
$numArr[$last[$d]] = $temp;
// Convert back to an integer and return
return intval(implode('', $numArr));
}
}
}
// If no swap was made, return the original number
return $num;
}
// Example usage:
echo maximumSwap(2736); // Output: 7236
echo maximumSwap(9973); // Output: 9973
?> Explanation:
Complexity:
This solution efficiently finds the maximum value by swapping digits only once, as required. |
Beta Was this translation helpful? Give feedback.
2 replies
Answer selected by
mah-shamim
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
We can follow a greedy approach. Here's a step-by-step explanation and the solution:
Approach: