Remove minimum number of elements such that no common element exist in both array | CPP program to find minimum element to remove so no common element exist in both array ; To find no elements to remove so no common element exist ; To store count of array element ; Count elements of a ; Count elements of b ; Traverse through all common element , and pick minimum occurrence from two arrays ; To return count of minimum elements ; Driver program to test minRemove ( )
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minRemove ( int a [ ] , int b [ ] , int n , int m ) { unordered_map < int , int > countA , countB ; for ( int i = 0 ; i < n ; i ++ ) countA [ a [ i ] ] ++ ; for ( int i = 0 ; i < m ; i ++ ) countB [ b [ i ] ] ++ ; int res = 0 ; for ( auto x : countA ) if ( countB . find ( x . first ) != countB . end ( ) ) res += min ( x . second , countB [ x . first ] ) ; return res ; } int main ( ) { int a [ ] = { 1 , 2 , 3 , 4 } ; int b [ ] = { 2 , 3 , 4 , 5 , 8 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; int m = sizeof ( b ) / sizeof ( b [ 0 ] ) ; cout << minRemove ( a , b , n , m ) ; return 0 ; }