Count of array elements whose order of deletion precedes order of insertion | Java 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 java . util . * ; class GFG { static void maximumCount ( int A [ ] , int B [ ] , int n ) { Queue < Integer > q = new LinkedList < > ( ) ; HashSet < Integer > s = new HashSet < > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { s . add ( B [ i ] ) ; q . add ( B [ i ] ) ; } int count = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( ! s . contains ( A [ i ] ) ) continue ; while ( ! q . isEmpty ( ) && q . peek ( ) != A [ i ] ) { s . remove ( q . peek ( ) ) ; q . remove ( ) ; count ++ ; } if ( A [ i ] == q . peek ( ) ) { q . remove ( ) ; s . remove ( A [ i ] ) ; } if ( q . isEmpty ( ) ) break ; } System . out . print ( count + "NEW_LINE"); } public static void main ( String [ ] args ) { int N = 4 ; int A [ ] = { 1 , 2 , 3 , 4 } ; int B [ ] = { 1 , 2 , 4 , 3 } ; maximumCount ( A , B , N ) ; } }