Count of array elements whose order of deletion precedes order of insertion | Python3 Program to implement the above approach ; 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
import queue NEW_LINE def maximumCount ( A , B , n ) : NEW_LINE INDENT q = queue . Queue ( ) NEW_LINE s = set ( ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT s . add ( B [ i ] ) NEW_LINE q . put ( B [ i ] ) NEW_LINE DEDENT count = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( A [ i ] not in s ) : NEW_LINE INDENT continue NEW_LINE DEDENT while ( q . qsize ( ) > 0 and q . queue [ 0 ] != A [ i ] ) : NEW_LINE INDENT s . remove ( q . queue [ 0 ] ) ; NEW_LINE q . get ( ) NEW_LINE count += 1 NEW_LINE DEDENT if ( A [ i ] == q . queue [ 0 ] ) : NEW_LINE INDENT q . get ( ) NEW_LINE s . remove ( A [ i ] ) NEW_LINE DEDENT if ( q . qsize ( ) == 0 ) : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT print ( count ) NEW_LINE DEDENT N = 4 NEW_LINE A = [ 1 , 2 , 3 , 4 ] NEW_LINE B = [ 1 , 2 , 4 , 3 ] NEW_LINE maximumCount ( A , B , N ) NEW_LINE