LeetCode 2231: Largest Number After Digit Swaps by Parity

Problem Description

Explanation

To find the largest possible value of the given number after swapping digits with the same parity, we can follow these steps:

  1. Separate the digits of the number into two lists, one for even digits and one for odd digits.
  2. Sort both lists in descending order.
  3. Combine the digits from both lists to form the largest number while ensuring that we swap digits only within the same parity group.

Time complexity: O(n log n) where n is the number of digits in the input number. Space complexity: O(n)

Solutions

class Solution {
    public int maximumSwap(int num) {
        char[] digits = String.valueOf(num).toCharArray();
        int[] lastIndexes = new int[10];
        
        for (int i = 0; i < digits.length; i++) {
            lastIndexes[digits[i] - '0'] = i;
        }
        
        for (int i = 0; i < digits.length; i++) {
            for (int j = 9; j > digits[i] - '0'; j--) {
                if (lastIndexes[j] > i) {
                    char temp = digits[i];
                    digits[i] = digits[lastIndexes[j]];
                    digits[lastIndexes[j]] = temp;
                    return Integer.parseInt(new String(digits));
                }
            }
        }
        
        return num;
    }
}

Loading editor...