fork download
  1. import java.util.*;
  2.  
  3. public class Main {
  4. public static void main(String[] args) {
  5. Scanner sc = new Scanner(System.in);
  6. int n = sc.nextInt();
  7. int k = sc.nextInt();
  8.  
  9. int[] nums = new int[n];
  10. for (int i = 0; i < n; i++) {
  11. nums[i] = sc.nextInt();
  12. }
  13. int cnt = 0;
  14. int sum = 0;
  15.  
  16. // Number of subarrays whose sum <= K (All numbers in the array>=0)
  17.  
  18.  
  19. for (int i = 0, j = 0; j < n; j++) {
  20. sum += nums[j];
  21. while (sum > k) {
  22. sum -= nums[i];
  23. i++;
  24. }
  25. cnt += (j - i + 1);
  26. }
  27. System.out.println(cnt);
  28. sc.close();
  29. }
  30. }
  31.  
Success #stdin #stdout 0.11s 54616KB
stdin
15 4 
1 2 3 5 8 8 8 8 2 1 1 1 1 1 9 
stdout
21