fork download
  1. import java.util.*;
  2.  
  3. public class Main {
  4. public static void main(String[] args) {
  5. int[] nums = {1, 2, 3};
  6. int k = 4;
  7.  
  8. System.out.println("Count of subarrays with sum >= K: " + countSubarrays(nums, k));
  9. }
  10.  
  11. public static long countSubarrays(int[] nums, int k) {
  12. int n = nums.length;
  13. long totalSubarrays = (long) n * (n + 1) / 2;
  14. if (k <= 0) return totalSubarrays;
  15.  
  16. // Single sliding window loop to directly count subarrays with sum <= k - 1
  17. long countLessThanK = 0;
  18. long currentSum = 0;
  19. int left = 0;
  20. int target = k - 1;
  21.  
  22. for (int right = 0; right < n; right++) {
  23. currentSum += nums[right];
  24.  
  25. while (currentSum > target && left <= right) {
  26. currentSum -= nums[left];
  27. left++;
  28. }
  29.  
  30. countLessThanK += (right - left + 1);
  31. }
  32.  
  33. return totalSubarrays - countLessThanK;
  34. }
  35. }
  36.  
Success #stdin #stdout 0.11s 53580KB
stdin
Standard input is empty
stdout
Count of subarrays with sum >= K: 2