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
#include <bits/stdc++.h> NEW_LINE using namespace std ; int maximumCount ( int A [ ] , int B [ ] , int n ) { queue < int > q ; unordered_set < int > s ; for ( int i = 0 ; i < n ; i ++ ) { s . insert ( B [ i ] ) ; q . push ( B [ i ] ) ; } int count = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( s . find ( A [ i ] ) == s . end ( ) ) continue ; while ( ! q . empty ( ) && q . front ( ) != A [ i ] ) { s . erase ( q . front ( ) ) ; q . pop ( ) ; count ++ ; } if ( A [ i ] == q . front ( ) ) { q . pop ( ) ; s . erase ( A [ i ] ) ; } if ( q . empty ( ) ) break ; } cout << count << endl ; } int main ( ) { int N = 4 ; int A [ ] = { 1 , 2 , 3 , 4 } ; int B [ ] = { 1 , 2 , 4 , 3 } ; maximumCount ( A , B , N ) ; return 0 ; }