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. Scanner sc=new Scanner(System.in);
  13. //this is target sum
  14. int sum=sc.nextInt();
  15. int n=sc.nextInt();
  16. int arr[]=new int[n];
  17. for(int i=0;i<n;i++){
  18. arr[i]=sc.nextInt();
  19. }
  20. int count=0;
  21. HashMap<Integer,Integer>hm=new HashMap<>();
  22. for(int i=0;i<n;i++){
  23. int targetValue=sum-arr[i];
  24. if(hm.containsKey(targetValue)){
  25. int valueCount=hm.get(targetValue);
  26. count+=valueCount;
  27.  
  28. }
  29. hm.put(arr[i],hm.getOrDefault(arr[i],0)+1);
  30. }
  31. System.out.print(count);
  32. }}
Success #stdin #stdout 0.18s 56272KB
stdin
4
6
2
4
2
3
2
4
stdout
3