Given an array arr [ ] , find the maximum j | C # implementation of the hashmap approach ; Function to find maximum index difference ; Initilaise unordered_map ; Iterate from 0 to n - 1 ; Sort arr ; Iterate from 0 to n - 1 ; Driver Code ; Function Call
using System ; using System . Collections . Generic ; public class GFG { static int maxIndexDiff ( List < int > arr , int n ) { Dictionary < int , List < int > > hashmap = new Dictionary < int , List < int > > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( hashmap . ContainsKey ( arr [ i ] ) ) { hashmap [ arr [ i ] ] . Add ( i ) ; } else { hashmap . Add ( arr [ i ] , new List < int > ( ) ) ; hashmap [ arr [ i ] ] . Add ( i ) ; } } arr . Sort ( ) ; int maxDiff = - 1 ; int temp = n ; for ( int i = 0 ; i < n ; i ++ ) { if ( temp > hashmap [ arr [ i ] ] [ 0 ] ) { temp = hashmap [ arr [ i ] ] [ 0 ] ; } maxDiff = Math . Max ( maxDiff , hashmap [ arr [ i ] ] [ hashmap [ arr [ i ] ] . Count - 1 ] - temp ) ; } return maxDiff ; } static public void Main ( ) { int n = 9 ; List < int > arr = new List < int > ( ) ; arr . Add ( 34 ) ; arr . Add ( 8 ) ; arr . Add ( 10 ) ; arr . Add ( 3 ) ; arr . Add ( 2 ) ; arr . Add ( 80 ) ; arr . Add ( 30 ) ; arr . Add ( 33 ) ; arr . Add ( 1 ) ; int ans = maxIndexDiff ( arr , n ) ; Console . WriteLine ( " The ▁ maxIndexDiff ▁ is ▁ : ▁ " + ans ) ; } }