fork download
  1. import java.util.*;
  2.  
  3. class Main {
  4. public static void main(String[] args) {
  5.  
  6. int[] nums = new int[]{1, 2, 3};
  7. int n = nums.length;
  8. int target = 4;
  9. int k = target - 1;
  10.  
  11.  
  12. int totalSubarrays = n * (n + 1) / 2;
  13.  
  14.  
  15. int left = 0;
  16. int countLessThanEqualK = 0;
  17. int sum = 0;
  18.  
  19. for (int right = 0; right < n; right++) {
  20. sum += nums[right];
  21.  
  22.  
  23. while (sum > k) {
  24. sum -= nums[left];
  25. left++;
  26. }
  27.  
  28.  
  29. countLessThanEqualK += (right - left + 1);
  30. }
  31.  
  32.  
  33. int result = totalSubarrays - countLessThanEqualK;
  34.  
  35. System.out.println(result);
  36. }
  37. }
  38.  
Success #stdin #stdout 0.07s 54604KB
stdin
Standard input is empty
stdout
2