Minimum cost required to rearrange a given array to make it equal to another given array | C ++ program for the above approach ; Function to find length of the longest common subsequence ; Find position where element is to be inserted ; Return the length of LCS ; Function to find the minimum cost required to convert the sequence A exactly same as B ; Auxiliary array ; Stores positions of elements of A [ ] ; Initialize index array with - 1 ; Update the index array with index of corresponding elements of B ; Place only A 's array values  with its mapped values  into nums array ; Find LCS ; No of elements to be added in array A [ ] ; Stores minimum cost ; Print the minimum cost ; Driver Code ; Given array A [ ] ; Given C ; Size of arr A ; Size of arr B ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int findLCS ( int * nums , int N ) { int k = 0 ; for ( int i = 0 ; i < N ; i ++ ) { int pos = lower_bound ( nums , nums + k , nums [ i ] ) - nums ; nums [ pos ] = nums [ i ] ; if ( k == pos ) { k = pos + 1 ; } } return k ; } int minimumCost ( int * A , int * B , int M , int N , int C ) { int nums [ 1000000 ] ; int index [ 1000000 ] ; memset ( index , -1 , sizeof ( index ) ) ; for ( int i = 0 ; i < N ; i ++ ) { index [ B [ i ] ] = i ; } int k = 0 ; for ( int i = 0 ; i < M ; i ++ ) { if ( index [ A [ i ] ] != -1 ) { nums [ k ++ ] = index [ A [ i ] ] ; } } int lcs_length = findLCS ( nums , k ) ; int elements_to_be_added = N - lcs_length ; int min_cost = elements_to_be_added * C ; cout << min_cost ; } int main ( ) { int A [ ] = { 1 , 6 , 3 , 5 , 10 } ; int B [ ] = { 3 , 1 , 5 } ; int C = 2 ; int M = sizeof ( A ) / sizeof ( A [ 0 ] ) ; int N = sizeof ( B ) / sizeof ( B [ 0 ] ) ; minimumCost ( A , B , M , N , C ) ; return 0 ; }