Thursday, July 28, 2022
HomeWordPress DevelopmentMost Quantity by swapping digits between positions with identical parity

Most Quantity by swapping digits between positions with identical parity


View Dialogue

Enhance Article

Save Article

Like Article

Given a optimistic integer N, the duty is to search out the most important potential worth of N after any variety of swaps is made between digits which are current in positions with the identical parity.

Examples:

Enter: N = 12345
Output: 54321
Rationalization: Swap 1 with 5 [both in odd positions],  
and a couple of with 4 [both in even positions] to acquire 54321.

Enter: N = 738946
Output: 897643

 

Method: 

The issue may be solved by storing odd listed and even listed digits in two maxHeaps, and creating new quantity that has each parity listed digits sorted in decending order.

The next steps can be utilized to resolve this downside:

  • Initialize 2 maxHeaps even and odd.
  • Iterate over digits of the quantity and retailer even listed digits in even maxHeap and odd listed digits in odd maxHeap.
  • Create a brand new quantity by popping values from maxHeaps, now new quantity would have each even listed digits and odd listed digits in lowering order.
  • Return this quantity as it’s the most.

Beneath is the implementation of the above method.

C++

  

#embrace <bits/stdc++.h>

utilizing namespace std;

  

int largestInteger(int num)

{

    

    

    priority_queue<int> Even;

    priority_queue<int> Odd;

  

    int C = 0, t = num;

  

    

    whereas (t) {

        C++;

        t /= 10;

    }

  

    

    

    bool flag = C & 1 ? 1 : 0;

  

    

    

    whereas (num) {

        if (flag)

            Even.push(num % 10);

        else

            Odd.push(num % 10);

        flag = !flag;

        num /= 10;

    }

  

    

    int ans = 0;

  

    

    whereas (!Even.empty() && !Odd.empty()) {

        ans = (ans * 10 + Even.high());

        Even.pop();

        ans = (ans * 10 + Odd.high());

        Odd.pop();

    }

  

    

    

    if (C & 1)

        ans = ans * 10 + Even.high();

  

    

    return ans;

}

  

int fundamental()

{

    int N = 738946;

  

    

    cout << largestInteger(N) << endl;

    return 0;

}

Time Complexity: O(log N)
Auxiliary House: O(log N)

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments