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 void main (String[] args) throws java.lang.Exception
  11. {
  12. // your code goes here
  13. int[] arr = {1,2,3,4,5,6,7,1};
  14. System.out.println("max distance is "+ maxDistanceOfSimilarElements(arr));
  15.  
  16. }
  17. static int maxDistanceOfSimilarElements(int []arr){
  18.  
  19. HashMap<Integer,Integer> map = new HashMap<>();
  20. int max = 0;
  21.  
  22. for(int i=0;i<arr.length;i++){
  23. if(!map.containsKey(arr[i])){
  24. map.put(arr[i],i);
  25. } else {
  26. max = Math.max(max,i-map.get(arr[i]));
  27. }
  28.  
  29. }
  30. return max;
  31. }
  32. }
Success #stdin #stdout 0.12s 55540KB
stdin
Standard input is empty
stdout
max distance is 7