Saturday, May 8, 2021

Published May 08, 2021 by Anonymous with 0 comment

Minimum difference possible between two given numbers by rearranging their digits in the same order

  

#include <bits/stdc++.h>

using namespace std;

  

int minDifference(int X, int Y)

{

    

    int minDiff = INT_MAX;

  

    

    string x = to_string(X);

  

    

    string y = to_string(Y);

  

    

    int n = x.size();

  

    

    int a[2][n];

  

    

    for (int i = 0; i < 2; i++) {

  

        

        for (int j = 0; j < n; j++) {

  

            

            if (i == 0)

                a[i][j] = x[j] - '0';

  

            

            else

                a[i][j] = y[j] - '0';

        }

    }

  

    

    int p[n];

  

    

    for (int i = 0; i < n; i++)

        p[i] = i;

  

    

    do {

  

        

        int xx = INT_MIN;

  

        

        int yy = INT_MAX;

  

        

        for (int i = 0; i < 2; i++) {

  

            

            

            int num = 0;

  

            

            for (int j = 0; j < n; j++)

  

                

                num = num * 10 + a[i][p[j]];

  

            

            xx = max(xx, num);

  

            

            yy = min(yy, num);

        }

  

        

        minDiff = min(minDiff, xx - yy);

  

    } while (next_permutation(p, p + n));

  

    

    return minDiff;

}

  

int main()

{

    int X = 37198, Y = 44911;

    cout << minDifference(X, Y);

  

    return 0;

}

Adblock test (Why?)


Original page link

Best Cool Tech Gadgets

Top favorite technology gadgets
      edit

0 comments:

Post a Comment