Saturday, 1 August 2020

Maximum Distance Between Two Occurences Of Same Element - Hashing Problem

To find the maximum distance between two occurrences of same element, we can store the elements in hashmap and compare max index distance. Following is the implementation:


package hashTables;
import java.util.HashMap;
import java.util.Map;
public class MaxDistanceBtnOccurances {
public static int maxDistance(int arr[], int n) {
Map<Integer,Integer> hm = new HashMap<>();
int max =0,prevMax=0;
for(int i=0;i<n;i++) {
if(hm.containsKey(arr[i])) {
prevMax = i-hm.get(arr[i]);
if(prevMax>max)
max=prevMax;
}else
hm.put(arr[i],i);
}
return max;
}
public static void main(String[] args) {
int a4[]= {3,2,1,2,1,4,5,8,6,7,4,2};
System.out.println(maxDistance(a4, 12));
}
}

No comments:

Post a Comment