Minimum cost required to rearrange a given array to make it equal to another given array | 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 ; Prvar the minimum cost ; Given array A ; Given C ; Size of arr A ; Size of arr B ; Function call
function LowerBound ( a , k , x ) { var l = - 1 ; var r = k ; while ( l + 1 < r ) { var m = ( l + r ) >>> 1 ; if ( a [ m ] >= x ) { r = m ; } else { l = m ; } } return r ; } function findLCS ( nums , N ) { var k = 0 ; for ( i = 0 ; i < N ; i ++ ) { var pos = LowerBound ( nums , k , nums [ i ] ) ; nums [ pos ] = nums [ i ] ; if ( k == pos ) { k = pos + 1 ; } } return k ; } function minimumCost ( A , B , M , N , C ) { var nums = Array ( 100000 ) . fill ( 0 ) ; var index = Array ( 100000 ) . fill ( 0 ) ; for ( i = 0 ; i < 100000 ; i ++ ) index [ i ] = - 1 ; for ( i = 0 ; i < N ; i ++ ) { index [ B [ i ] ] = i ; } var k = 0 ; for ( i = 0 ; i < M ; i ++ ) { if ( index [ A [ i ] ] != - 1 ) { nums [ k ++ ] = index [ A [ i ] ] ; } } var lcs_length = findLCS ( nums , k ) ; var elements_to_be_added = N - lcs_length ; var min_cost = elements_to_be_added * C ; document . write ( min_cost ) ; return 0 ; } var A = [ 1 , 6 , 3 , 5 , 10 ] ; var B = [ 3 , 1 , 5 ] ; var C = 2 ; var M = A . length ; var N = B . length ; minimumCost ( A , B , M , N , C ) ;