Untitled

 avatar
unknown
plain_text
a month ago
840 B
0
Indexable
class Solution {
    public int numSubarraysWithSum(int[] nums, int goal) {
        return atMost(nums, goal) - atMost(nums, goal - 1);
    }

    // Helper method to count subarrays with at most `target` sum
    private int atMost(int[] nums, int target) {
        if (target < 0) return 0; // Edge case: negative target
        int i = 0, count = 0, sum = 0;
        
        for (int j = 0; j < nums.length; j++) {
            sum += nums[j]; // Add current element to the window
            
            // Shrink the window if the sum exceeds the target
            while (sum > target) {
                sum -= nums[i];
                i++;
            }
            
            // Add the number of subarrays ending at `j`
            count += (j - i + 1);
        }
        
        return count;
    }
}
Leave a Comment