fork download
  1. import java.util.Scanner;
  2.  
  3. public class Main {
  4. public static void main(String[] args) {
  5. Scanner scanner = new Scanner(System.in);
  6.  
  7. // Reading the size of the array
  8. int n = scanner.nextInt();
  9.  
  10. // Reading the maximum allowed subarray sum limit
  11. long k = scanner.nextLong();
  12.  
  13. // Initialize the array
  14. long[] b = new long[n];
  15. for (int i = 0; i < n; i++) {
  16. b[i] = scanner.nextLong();
  17. }
  18.  
  19. long count = 0;
  20. long currentSum = 0;
  21. // Left pointer of the sliding window
  22. int i = 0;
  23.  
  24. // Loop with 'j' acting as the right pointer
  25. for (int j = 0; j < n; j++) {
  26. currentSum += b[j];
  27.  
  28. // Shrink the window from the left if the sum exceeds k
  29. while (currentSum > k && i <= j) {
  30. currentSum -= b[i];
  31. i++;
  32. }
  33.  
  34. // Count all valid subarrays ending at index j
  35. count += (j - i + 1);
  36. }
  37.  
  38. System.out.println(count);
  39. scanner.close();
  40. }
  41. }
  42.  
Success #stdin #stdout 0.11s 54520KB
stdin
5
4
1 2 1 1 1
stdout
12