fork download
  1. import java.util.*;
  2. import java.lang.*;
  3. class Solution {
  4.  
  5. public static void main (String[] args) throws java.lang.Exception
  6. {
  7. Scanner sc = new Scanner(System.in);
  8. int size = sc.nextInt();
  9.  
  10. int[] arr =new int[size];
  11.  
  12. for(int i = 0;i<size;i++){
  13. arr[i] = sc.nextInt();
  14. }
  15.  
  16.  
  17. int q = sc.nextInt();
  18. for (int i = 0; i < q; i++) {
  19.  
  20. int result = maxDistance(arr);
  21. System.out.println(result);
  22. }
  23. }
  24. public static int maxDistance(int[] arr) {
  25. // Code here
  26. HashMap<Integer,Integer> map = new HashMap<>();
  27.  
  28. int n = arr.length;
  29. int maxDist = 0;
  30. for(int i=0;i<n; i++){
  31. if(map.containsKey(arr[i])){
  32. // Calculate actual distance from the FIRST occurrence
  33. int dist = Math.abs(i - map.get(arr[i]) );
  34. maxDist = Math.max(dist,maxDist);
  35. }else{
  36. // Only store the very first time you see the number
  37. map.put(arr[i],i);
  38. }
  39.  
  40. }
  41.  
  42. return maxDist;
  43. }
  44. }
Success #stdin #stdout 0.13s 56584KB
stdin
3
2 2 1
1
2
stdout
1