Minimum cost required to rearrange a given array to make it equal to another given array | Java program for the above approach ; Function to find lower_bound ; 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
import java . io . * ; class GFG { static int LowerBound ( int a [ ] , int k , int x ) { int l = - 1 ; int r = k ; while ( l + 1 < r ) { int m = ( l + r ) >>> 1 ; if ( a [ m ] >= x ) { r = m ; } else { l = m ; } } return r ; } static int findLCS ( int [ ] nums , int N ) { int k = 0 ; for ( int i = 0 ; i < N ; i ++ ) { int pos = LowerBound ( nums , k , nums [ i ] ) ; nums [ pos ] = nums [ i ] ; if ( k == pos ) { k = pos + 1 ; } } return k ; } static int minimumCost ( int [ ] A , int [ ] B , int M , int N , int C ) { int [ ] nums = new int [ 100000 ] ; int [ ] index = new int [ 100000 ] ; for ( int i = 0 ; i < 100000 ; i ++ ) index [ i ] = - 1 ; 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 ; System . out . println ( min_cost ) ; return 0 ; } public static void main ( String [ ] args ) { int [ ] A = { 1 , 6 , 3 , 5 , 10 } ; int [ ] B = { 3 , 1 , 5 } ; int C = 2 ; int M = A . length ; int N = B . length ; minimumCost ( A , B , M , N , C ) ; } }