text: Count elements of same value placed at same indices of two given arrays | Java program for the above approach ; Function to count maximum matched elements from the arrays A [ ] and B [ ] ; Stores position of elements of array A [ ] in the array B [ ] ; Keep track of difference between the indices ; Traverse the array A [ ] ; Traverse the array B [ ] ; If difference is negative , add N to it ; Keep track of the number of shifts required to place elements at same indices ; Return the max matches ; Driver Code ; Returns the count of matched elements
code: import java . io . Console ; import java . util . HashMap ; import java . util . Map ; class GFG { static int maxMatch ( int [ ] A , int [ ] B ) { HashMap < Integer , Integer > Aindex = new HashMap < Integer , Integer > ( ) ; HashMap < Integer , Integer > diff = new HashMap < Integer , Integer > ( ) ; for ( int i = 0 ; i < A . length ; i ++ ) { Aindex . put ( A [ i ] , i ) ; } for ( int i = 0 ; i < B . length ; i ++ ) { if ( i - Aindex . get ( B [ i ] ) < 0 ) { if ( ! diff . containsKey ( A . length + i - Aindex . get ( B [ i ] ) ) ) { diff . put ( A . length + i - Aindex . get ( B [ i ] ) , 1 ) ; } else { diff . put ( A . length + i - Aindex . get ( B [ i ] ) , diff . get ( A . length + i - Aindex . get ( B [ i ] ) ) + 1 ) ; } } else { if ( ! diff . containsKey ( i - Aindex . get ( B [ i ] ) ) ) { diff . put ( i - Aindex . get ( B [ i ] ) , 1 ) ; } else { diff . put ( i - Aindex . get ( B [ i ] ) , diff . get ( i - Aindex . get ( B [ i ] ) ) + 1 ) ; } } } int max = 0 ; for ( Map . Entry < Integer , Integer > ele : diff . entrySet ( ) ) { if ( ele . getValue ( ) > max ) { max = ele . getValue ( ) ; } } return max ; } public static void main ( String [ ] args ) { int [ ] A = { 5 , 3 , 7 , 9 , 8 } ; int [ ] B = { 8 , 7 , 3 , 5 , 9 } ; System . out . println ( maxMatch ( A , B ) ) ; } }