http://www.geeksforgeeks.org/maximum-distance-two-occurrences-element-array/
An efficient solution for this problem is to use hashing. The idea is to traverse input array and store index of first occurrence in a hash map. For every other occurrence, find the difference between index and the first index stored in hash map. If difference is more than result so far, then update the result.
An efficient solution for this problem is to use hashing. The idea is to traverse input array and store index of first occurrence in a hash map. For every other occurrence, find the difference between index and the first index stored in hash map. If difference is more than result so far, then update the result.
int
maxDistance(
int
arr[],
int
n)
{
// Used to store element to first index mapping
unordered_map<
int
,
int
> mp;
// Traverse elements and find maximum distance between
// same occurrences with the help of map.
int
max_dist = 0;
for
(
int
i=0; i<n; i++)
{
// If this is first occurrence of element, insert its
// index in map
if
(mp.find(arr[i]) == mp.end())
mp[arr[i]] = i;
// Else update max distance
else
max_dist = max(max_dist, i - mp[arr[i]]);
}
return
max_dist;
}