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. Scanner sc=new Scanner(System.in);
  14. int n=sc.nextInt();
  15. int k=sc.nextInt();
  16. int[] arr=new int[n+1];
  17. for(int i=1;i<=n;i++){
  18. arr[i]=sc.nextInt();
  19. }
  20. int[] ps=new int[n+1];
  21. for(int i=1;i<=n;i++){
  22. ps[i]=ps[i-1]+arr[i];
  23. }
  24. HashMap<Integer,Integer> map=new HashMap<>();
  25. map.put(0,0);
  26. int maxLen=0;
  27. for(int i=1;i<=n;i++){
  28. int rem=ps[i]-k;
  29. if(map.containsKey(rem)){
  30. maxLen = Math.max(maxLen, i - map.get(rem));
  31. }
  32. if(!map.containsKey(ps[i])){
  33. map.put(ps[i],i);
  34. }
  35. }
  36. int count=0;
  37. int i=1;
  38. int j=1;
  39. int sum=0;
  40. while(j<=n){
  41. sum+=arr[j];
  42. if(j-i+1<maxLen) j++;
  43. else if (j-i+1==maxLen) {
  44. if(sum==k) count++;
  45. sum-=arr[i];
  46. i++;
  47. j++;
  48. }
  49. }
  50. System.out.println(count+" whose length is "+maxLen);
  51. }
  52. }
Success #stdin #stdout 0.24s 60984KB
stdin
8
15
10 5 2 7 1 9 8 7
stdout
1 whose length is 4