fork download
  1. import java.util.*;
  2. import java.lang.*;
  3. import java.io.*;
  4.  
  5.  
  6. class Main {
  7. public static void main (String[] args) throws java.lang.Exception {
  8. Solution solution = new Solution();
  9.  
  10.  
  11. int[] nums1 = {2, 1, 4, 3, 5};
  12. long k1 = 10;
  13. System.out.println("Test Case 1 Result: " + solution.countSubarrays(nums1, k1));
  14.  
  15.  
  16. int[] nums2 = {100, 200, 300};
  17. long k2 = 5;
  18. System.out.println("Test Case 2 Result: " + solution.countSubarrays(nums2, k2));
  19. }
  20. }
  21.  
  22. class Solution {
  23. public long countSubarrays(int[] nums, long k) {
  24. int left = 0;
  25. long currentSum = 0;
  26. long count = 0;
  27.  
  28. for (int right = 0; right < nums.length; right++) {
  29. // Expand the window by adding the current element
  30. currentSum += nums[right];
  31.  
  32. // Shrink the window from the left while the score is invalid
  33. while (currentSum * (right - left + 1) >= k) {
  34. currentSum -= nums[left];
  35. left++;
  36. }
  37.  
  38. // Add the number of valid subarrays ending at 'right'
  39. count += (right - left + 1);
  40. }
  41.  
  42. return count;
  43. }
  44. }
  45.  
Success #stdin #stdout 0.1s 53524KB
stdin
Standard input is empty
stdout
Test Case 1 Result: 6
Test Case 2 Result: 0