Count Windows With Positive Sum
Given an integer array nums and a window size k, count how many contiguous subarrays of length k have a sum greater than 0 using the sliding window technique.
Maintain the running sum of the current window. Start by computing the sum of the first k elements. If this sum is greater than 0, initialize the counter to 1; otherwise 0. Then slide the window one position at a time from index k to the end of the array. For each slide, subtract the element that is leaving the window and add the new element that is entering. After updating the sum, check if it is greater than 0 and increment the counter accordingly.
The sliding window approach is O(n) time and O(1) space. Each element is processed exactly twice — once when it enters the window and once when it leaves — making this highly efficient. Without the sliding window technique, computing the sum for each window would require O(k) work per window, resulting in O(n*k) total time.
Edge cases include empty arrays (return 0), k larger than the array length (return 0), and arrays where no window has a positive sum (return 0). This problem is useful for analyzing consecutive data points where positive aggregate values indicate favorable periods.
Example Input & Output
Sums: 2, 5, 2 — all 3 > 0
All sums negative
[1,2]=3, [2,3]=5
Algorithm Flow

Solution Approach
Compute initial window sum. If sum > 0, count=1 else 0. Slide and update: when sum > 0, increment count.
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.
