fork download
  1. import java.util.*;
  2.  
  3. class Ideone {
  4. static int subarray(int arr[], int k) {
  5. int sum = 0;
  6. int count = 0;
  7. int n = arr.length;
  8. int i = 0, j = 0;
  9.  
  10. while (j < n) {
  11. sum += arr[j];
  12.  
  13. while (sum > k && i <= j) {
  14. sum -= arr[i];
  15. i++;
  16. }
  17.  
  18. count += (j - i + 1);
  19. j++;
  20. }
  21.  
  22. return count;
  23. }
  24.  
  25. public static void main(String[] args) throws java.lang.Exception {
  26. int[] arr = {1, 2, 3, 4};
  27. int k = 5;
  28. System.out.println("Count of subarrays: " + subarray(arr, k));
  29. }
  30. }
  31.  
Success #stdin #stdout 0.11s 55724KB
stdin
Standard input is empty
stdout
Count of subarrays: 6