Skip to content

Added max swaps sol #101

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 9 commits into from
Oct 27, 2024
31 changes: 31 additions & 0 deletions LeetCode/Algorithms/Medium/MaximumSwaps/MaximumSwaps.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
class MaximumSwaps {
public int maximumSwap(int num) {
// Convert number to string for digit manipulation
char[] numArr = Integer.toString(num).toCharArray();
int n = numArr.length;

// Track the last occurrence of each digit (0-9)
int[] last = new int[10];
for (int i = 0; i < n; i++) {
last[numArr[i] - '0'] = i;
}

// Traverse the number from left to right
for (int i = 0; i < n; i++) {
// Check if we can find a larger digit to swap
for (int d = 9; d > numArr[i] - '0'; d--) {
if (last[d] > i) {
// Swap and return the new number
char temp = numArr[i];
numArr[i] = numArr[last[d]];
numArr[last[d]] = temp;
return Integer.parseInt(new String(numArr));
}
}
}

// Return the original number if no swap occurred
return num;
}
}