Count of array elements whose order of deletion precedes order of insertion | C # 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
using System ; using System . Collections . Generic ; class GFG { static void maximumCount ( int [ ] A , int [ ] B , int n ) { Queue < int > q = new Queue < int > ( ) ; HashSet < int > s = new HashSet < int > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { s . Add ( B [ i ] ) ; q . Enqueue ( B [ i ] ) ; } int count = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( ! s . Contains ( A [ i ] ) ) continue ; while ( q . Count != 0 && q . Peek ( ) != A [ i ] ) { s . Remove ( q . Peek ( ) ) ; q . Dequeue ( ) ; count ++ ; } if ( A [ i ] == q . Peek ( ) ) { q . Dequeue ( ) ; s . Remove ( A [ i ] ) ; } if ( q . Count == 0 ) break ; } Console . Write ( count + " STRNEWLINE " ) ; } 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 ) ; } }