De-arrangements for minimum product sum of two arrays

Given two arrays A[] and B[] of same size n. We need to first permute any of arrays such that the sum of product of pairs( 1 element from each) is minimum. That is SUM ( Ai*Bi) for all i is minimum. We also need to count number of de-arrangements present in original array as compared to permuted array.


Input : A[] = {4, 3, 2},  
        B[] = {7, 12, 5}
Output : 3
Explanation : A[] = {4, 3, 2} and B[] = {5, 7, 12}
results in minimum product sum. B[] = {7, 12, 5} 
is 3-position different from new B[].

Input : A[] = {4, 3, 2},  
        B[] = { 1, 2, 3}
Output : 0
Explanation : A[] = {4, 3, 2} and B[] = {1, 2, 3}
results in minimum product sum. B[] = {1, 2, 3} 
is exactly same as new one.

Idea behind finding the minimum sum of product from two array is to sort both array one in increasing and other in decreasing manner. These type of arrays will always produce minimum sum of pair product. Sorting both array will give the pair value i.e. which element from A is paired to which element from B[]. After that count the de-arrangement from original arrays.
Algorithm :

  1. make a copy of both array.
  2. sort copy_A[] in increasing, copy_B[] in decreasing order.
  3. Iterate for all Ai, find Ai in copy_A[] as copy_A[j] and
    check whether copy_B[j] == B[i] or not. Increment count if not equal.
  4. Return Count Value. That will be our answer.




// CPP program to count de-arrangements for 
// minimum product.
using namespace std;
// function for finding de-arrangement
int findDearrange (int A[], int B[], int n)
    // create copy of array
    vector <int> copy_A (A, A+n);
    vector <int> copy_B (B, B+n);
    // sort array in inc & dec way
    sort(copy_A.begin(), copy_A.end());
    sort(copy_B.begin(), copy_B.end(),greater<int>());
    // count no. of de arrangements
    int count = 0;
    for (int i=0; i<n;i++)
         vector<int>::iterator itA;
         // find position of A[i] in sorted array
         itA = lower_bound(copy_A.begin(), 
                           copy_A.end(), A[i]);
         // check whether B[i] is same as required or not
         if (B[i] != copy_B[itA-copy_A.begin()])
    // return count
    return count;
// driver function
int main()
    int A[] = {1, 2, 3, 4};
    int B[] = {6, 3, 4, 5};
    int n = sizeof(A) /sizeof(A[0]);;
    cout << findDearrange(A,B,n);
    return 0;



Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

Discovering ways to develop a plane for soaring career goals

If you like GeeksforGeeks and would like to contribute, you can also write an article using or mail your article to See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.

Article Tags :
Practice Tags :