Maximum Number by swapping digits between positions with same parity
Given a positive integer N, the task is to find the largest possible value of N after any number of swaps is made between digits that are present in positions with the same parity.
Input: N = 12345
Explanation: Swap 1 with 5 [both in odd positions],
and 2 with 4 [both in even positions] to obtain 54321.
Input: N = 738946
The problem can be solved by storing odd indexed and even indexed digits in two maxHeaps, and creating new number that has both parity indexed digits sorted in descending order.
The following steps can be used to solve this problem:
- Initialize 2 maxHeaps even and odd.
- Iterate over digits of the number and store even indexed digits in even maxHeap and odd indexed digits in odd maxHeap.
- Create a new number by popping values from maxHeaps, now new number would have both even indexed digits and odd indexed digits in decreasing order.
- Return this number as it is the maximum.
Below is the implementation of the above approach.
Time Complexity: O(log N)
Auxiliary Space: O(log N)