fork download
  1.  
  2. import java.util.*;
  3. import java.lang.*;
  4. import java.io.*;
  5.  
  6. class Main {
  7. public static void main(String[] args) {
  8. int[] arr = new int[]{1, 1, 1, 4, 5, 6};
  9. int k = 12;
  10.  
  11. int totalSubarraysCount = 0;
  12. int currentWindowSum = 0;
  13. int left = 0;
  14.  
  15. // 'right' expands the window forward
  16. for (int right = 0; right < arr.length; right++) {
  17. currentWindowSum += arr[right];
  18.  
  19. // If the sum exceeds k, contract the window from the left
  20. while (currentWindowSum > k && left <= right) {
  21. currentWindowSum -= arr[left];
  22. left++;
  23. }
  24.  
  25. // O(1) Counting Step:
  26. // All valid subarrays ending at 'right' are counted at once.
  27. int windowSize = right - left + 1;
  28. totalSubarraysCount += windowSize;
  29. }
  30.  
  31. System.out.println("Total subarrays with sum <= k is " + totalSubarraysCount);
  32. }
  33. }
  34.  
Success #stdin #stdout 0.11s 55512KB
stdin
Standard input is empty
stdout
Total subarrays with sum <= k is 17