Count of array elements whose order of deletion precedes order of insertion | Function returns maximum number of required elements ; Insert the elements of array B in the queue and set ; Stores the answer ; If A [ i ] is already processed ; Until we find A [ i ] in the queue ; Remove elements from the queue ; Increment the count ; Remove the current element A [ i ] from the queue and set . ; Return total count ; Driver Code
function maximumCount ( A , B , n ) { var q = [ ] ; var s = new Set ( ) ; for ( var i = 0 ; i < n ; i ++ ) { s . add ( B [ i ] ) ; q . push ( B [ i ] ) ; } var count = 0 ; for ( var i = 0 ; i < n ; i ++ ) { if ( s . has ( A [ i ] ) ) { while ( q . length != 0 && q [ 0 ] != A [ i ] ) { s . delete ( q [ 0 ] ) ; q . shift ( ) ; count ++ ; } if ( A [ i ] == q [ 0 ] ) { q . shift ( ) ; s . delete ( A [ i ] ) ; } if ( q . length == 0 ) break ; } } document . write ( count ) ; } var N = 4 ; var A = [ 1 , 2 , 3 , 4 ] ; var B = [ 1 , 2 , 4 , 3 ] ; maximumCount ( A , B , N ) ;