C++ simple and short 10-line O(n) solution, no extra space except a string

  • 0
        int maximumSwap(int num) {
            string s=to_string(num);
            for(int i=0;i<s.size();i++) {
                int max=s.back()-'0', pos=s.size()-1;
                for(int j=s.size()-2;j>i;j--) {
                    if(s[j]-'0'>max) max=s[j]-'0', pos=j;
                if(max>s[i]-'0') {
                    swap(s[i], s[pos]);
                    return stoi(s);
            return num;

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.