0% found this document useful (0 votes)
9 views1 page

Maximum Swap

Uploaded by

hatshthegreat
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views1 page

Maximum Swap

Uploaded by

hatshthegreat
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 1

class Solution {

public:
int maximumSwap(int num) {

string digits = to_string(num);

// Create a vector to store the last occurrence of each digit (0 to 9)


vector<int> last(10, -1);

// Fill the last occurrence of each digit


for (int i = 0; i < digits.size(); i++) {
last[digits[i] - '0'] = i;
}

// Traverse the digits to find the first opportunity to swap


for (int i = 0; i < digits.size(); i++) {
// Check if there is a larger digit later in the number
for (int d = 9; d > digits[i] - '0'; d--) {
if (last[d] > i) {
// Swap the current digit with the later larger digit
swap(digits[i], digits[last[d]]);
// Return the modified number after the swap
return stoi(digits);
}
}
}

// If no swap is made, return the original number


return num;
}
};

You might also like