Maximum distance between two occurrences of same element in array | C # program to find maximum distance between two same occurrences of a number . ; Function to find maximum distance between equal elements ; Used to store element to first index mapping ; Traverse elements and find maximum distance between same occurrences with the help of map . ; If this is first occurrence of element , insert its index in map ; Else update max distance ; Driver code
using System ; using System . Collections . Generic ; class GFG { static int maxDistance ( int [ ] arr , int n ) { Dictionary < int , int > map = new Dictionary < int , int > ( ) ; int max_dist = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( ! map . ContainsKey ( arr [ i ] ) ) map . Add ( arr [ i ] , i ) ; else max_dist = Math . Max ( max_dist , i - map [ arr [ i ] ] ) ; } return max_dist ; } public static void Main ( String [ ] args ) { int [ ] arr = { 3 , 2 , 1 , 2 , 1 , 4 , 5 , 8 , 6 , 7 , 4 , 2 } ; int n = arr . Length ; Console . WriteLine ( maxDistance ( arr , n ) ) ; } }