fork download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.io.*;
  6.  
  7. /* Name of the class has to be "Main" only if the class is public. */
  8. class Ideone
  9. {
  10. public static int maxDistance(int[] arr) {
  11. // Code here
  12. Map<Integer,Integer> indexMap=new HashMap<>();
  13. int maxDiff=0;
  14. for(int i=0;i<arr.length;i++){
  15. if(indexMap.containsKey(arr[i])){
  16. maxDiff=Math.max(maxDiff,i-indexMap.get(arr[i]));
  17. }
  18. else{
  19. indexMap.put(arr[i],i);
  20. }
  21. }
  22. return maxDiff;
  23. }
  24.  
  25. public static void main(String [] args){
  26. Scanner sc=new Scanner(System.in);
  27. int n=sc.nextInt();
  28. int [] arr=new int[n];
  29. for(int i=0;i<n;i++){
  30. arr[i]=sc.nextInt();
  31. }
  32. int dist=maxDistance(arr);
  33. System.out.println("Max Distance Between Two Occurrences is :"+dist);
  34. sc.close();
  35. }
  36. }
Success #stdin #stdout 0.21s 56908KB
stdin
12
3 2 1 2 1 4 5 8 6 7 4 2
stdout
Max Distance Between Two Occurrences is :10