Count Windows With Negative Sum
Given an integer array and window size k, count how many contiguous subarrays of length k have a sum less than 0 using the sliding window technique.
This is the complement of the positive-sum problem. Maintain the running window sum. After each slide, check if the sum is negative and increment the counter. The sliding window update subtracts the leaving element and adds the entering element in O(1) time per slide.
The time complexity is O(n) with a single pass through the array. The space complexity is O(1) using only integer variables for the running sum and the count.
Edge cases include empty arrays (return 0), k larger than array length (return 0), and arrays where all window sums are non-negative (return 0).
This is the complement of the positive-sum problem and follows the same sliding window pattern. The condition check is simply inverted from > 0 to
< 0.The window-sum-negative problem is the direct complement of window-sum-positive. Together, these two problems show how the same sliding window pattern can be adapted to different threshold conditions. The running sum update is identical — only the comparison operator changes from > 0 to < 0. This demonstrates the versatility of the sliding window approach across different problem requirements.
Example Input & Output
[0,-1]=-1, [-1,-2]=-3
Only [-5,4]=-1 is negative
Only [-1,-2]=-3 is negative
Algorithm Flow

Solution Approach
Track running sum. Count when sum
< 0.Best Answers
class Solution {
public int solution(int[] nums, int k) {
if (nums.length<k) return 0;
int s=0;for(int i=0;i<k;i++)s+=nums[i];
int r=s<0?1:0;
for(int i=k;i<nums.length;i++){s+=nums[i]-nums[i-k];if(s<0)r++;}
return r;
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
