Skip to content

670. Maximum Swap #711

Answered by kovatz
mah-shamim asked this question in Q&A
Oct 17, 2024 · 1 comments · 2 replies
Discussion options

You must be logged in to vote

We can follow a greedy approach. Here's a step-by-step explanation and the solution:

Approach:

  1. Convert the Number to an Array: Since digits need to be swapped, converting the number into an array of digits makes it easier to access and manipulate individual digits.
  2. Track the Rightmost Occurrence of Each Digit: Store the rightmost position of each digit (0-9) in an array.
  3. Find the Best Swap Opportunity: Traverse through the number's digits from left to right, and for each digit, check if there is a higher digit that appears later. If so, swap them to maximize the number.
  4. Perform the Swap and Break: As soon as the optimal swap is found, perform the swap and break the loop.
  5. Convert the Arra…

Replies: 1 comment 2 replies

Comment options

You must be logged in to vote
2 replies
@mah-shamim
Comment options

mah-shamim Oct 17, 2024
Maintainer Author

@kovatz
Comment options

kovatz Oct 17, 2024
Collaborator

Answer selected by mah-shamim
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
question Further information is requested medium Difficulty hacktoberfest hacktoberfest hacktoberfest-accepted hacktoberfest accepted
2 participants