fork download
  1.  
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.io.*;
  6.  
  7.  
  8. class Main {
  9. public static void main(String[] args) {
  10. int[] arr = new int[]{1, 1, 1, 4, 5, 6};
  11. int k = 12;
  12. int count = 0;
  13. int sum = 0;
  14.  
  15. // Two pointers: 'left' and 'right'
  16. int left = 0;
  17.  
  18. for (int right = 0; right < arr.length; right++) {
  19. // Expand the window by adding the element at 'right'
  20. sum += arr[right];
  21.  
  22. // Shrink the window from the left if the sum exceeds k
  23. while (sum > k && left <= right) {
  24. sum -= arr[left];
  25. left++;
  26. }
  27.  
  28. // If the window [left...right] is valid (sum <= k),
  29. // then all subarrays ending at 'right' and starting from 'left' up to 'right' are also valid.
  30. count += (right - left + 1);
  31. }
  32.  
  33. System.out.println("Total subarrays with sum <= k is " + count);
  34. }
  35. }
  36.  
Success #stdin #stdout 0.12s 55640KB
stdin
Standard input is empty
stdout
Total subarrays with sum <= k is 17