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 scanner = new Scanner(System.in);
  13. int n = scanner.nextInt();
  14. int k = scanner.nextInt();
  15. int[] nums = new int[n];
  16.  
  17. for (int i = 0; i < n; i++) {
  18. nums[i] = scanner.nextInt();
  19. }
  20. int res = countSubWithSumLessThenEqualK(nums,k);
  21. System.out.println(res);
  22. }
  23.  
  24.  
  25. public static int countSubWithSumLessThenEqualK(int []nums,int k){
  26. int cnt=0;
  27. int l=0,r=0;
  28. int psum=0,len=0,actual = 0,n=nums.length;
  29. while(l<n && r<n){
  30. psum+=nums[r];
  31. r++;
  32. len++;
  33. while(psum > k && l < n){
  34. psum-=nums[l];
  35. l++;
  36. len--;
  37. }
  38. if(psum <= k) cnt+=len;
  39. }
  40. return cnt;
  41. }
  42.  
  43.  
  44. }
Success #stdin #stdout 0.11s 54456KB
stdin
6 4
2 1 1 8 2 2
stdout
9