670. Maximum Swap
Input: 2736
Output: 7236
Explanation: Swap the number 2 and the number 7.Input: 9973
Output: 9973
Explanation: No swap.// Brute Force
int maximumSwap(int num) { // time: O(n^2); space: O(n)
string str = to_string(num);
int res = num, n = str.length();
for (int i = 0; i < n; ++i) {
for (int j = i + 1; j < n; ++j) {
swap(str[i], str[j]);
res = max(res, stoi(str) );
swap(str[i], str[j]);
}
}
return res;
}Last updated