text: 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
code: #include <bits/stdc++.h> NEW_LINE using namespace std ; int maxIndexDiff ( vector < int > & arr , int n ) { unordered_map < int , vector < int > > hashmap ; for ( int i = 0 ; i < n ; i ++ ) { hashmap [ arr [ i ] ] . push_back ( i ) ; } sort ( arr . begin ( ) , arr . end ( ) ) ; int maxDiff = INT_MIN ; int temp = n ; for ( int i = 0 ; i < n ; i ++ ) { if ( temp > hashmap [ arr [ i ] ] [ 0 ] ) { temp = hashmap [ arr [ i ] ] [ 0 ] ; } maxDiff = max ( maxDiff , hashmap [ arr [ i ] ] [ hashmap [ arr [ i ] ] . size ( ) - 1 ] - temp ) ; } return maxDiff ; } int main ( ) { int n = 9 ; vector < int > arr { 34 , 8 , 10 , 3 , 2 , 80 , 30 , 33 , 1 } ; int ans = maxIndexDiff ( arr , n ) ; cout << " The ▁ maxIndexDiff ▁ is ▁ : ▁ " << ans << endl ; return 1 ; }