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 sol(int arr[],int k){
  11. int n=arr.length;
  12. int count=Integer.MAX_VALUE;
  13. Map<Integer,Integer>mp=new HashMap<>();
  14. for(int i=n-1;i>=0;i--){
  15. if(mp.containsKey(k-arr[i])){
  16. int idx=mp.get(k-arr[i]);
  17. count=Math.min(count,idx-i+1);
  18. }
  19. mp.put(arr[i],i);
  20. }
  21. return count;
  22. }
  23. public static void main (String[] args) throws java.lang.Exception
  24. {
  25. // your code goes here
  26. Scanner sc=new Scanner(System.in);
  27. int n=sc.nextInt();
  28.  
  29. int arr[]=new int[n];
  30. for(int i=0;i<n;i++) arr[i]=sc.nextInt();
  31.  
  32. int target=sc.nextInt();
  33.  
  34. System.out.println(sol(arr,target));
  35. }
  36. }
Success #stdin #stdout 0.16s 54564KB
stdin
5
1 5 3 7 9
8
stdout
2