Skip to content

Latest commit

 

History

History

2231

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 

You are given a positive integer num. You may swap any two digits of num that have the same parity (i.e. both odd digits or both even digits).

Return the largest possible value of num after any number of swaps.

 

Example 1:

Input: num = 1234
Output: 3412
Explanation: Swap the digit 3 with the digit 1, this results in the number 3214.
Swap the digit 2 with the digit 4, this results in the number 3412.
Note that there may be other sequences of swaps but it can be shown that 3412 is the largest possible number.
Also note that we may not swap the digit 4 with the digit 1 since they are of different parities.

Example 2:

Input: num = 65875
Output: 87655
Explanation: Swap the digit 8 with the digit 6, this results in the number 85675.
Swap the first digit 5 with the digit 7, this results in the number 87655.
Note that there may be other sequences of swaps but it can be shown that 87655 is the largest possible number.

 

Constraints:

  • 1 <= num <= 109

Similar Questions:

Solution 1.

// OJ: https://leetcode.com/problems/largest-number-after-digit-swaps-by-parity/
// Author: github.com/lzl124631x
// Time: O(KlogK) where K is the number of digits in `n`
// Space: O(K)
class Solution {
public:
    int largestInteger(int n) {
        vector<int> odd, even;
        auto s = to_string(n);
        for (int i = 0; i < s.size(); ++i) {
            if ((s[i] - '0') % 2) odd.push_back(i);
            else even.push_back(i);
        }
        auto cmp = [&](int a, int b) { return s[a] > s[b]; };
        sort(begin(odd), end(odd), cmp);
        sort(begin(even), end(even), cmp);
        int ans = 0;
        for (int i = 0, j = 0, k = 0; i < s.size(); ++i) {
            if ((s[i] - '0') % 2) ans = ans * 10 + (s[odd[j++]] - '0');
            else ans = ans * 10 + (s[even[k++]] - '0');
        }
        return ans;
    }
};