Code Logo

Count Windows With Positive Sum

Published at24 Jul 2026
Easy 0 views
Like0

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

Example 1
Input
[],2
Output
0
Example 2
Input
[1,-2,3,4,-5],3
Output
3
Explanation

Sums: 2, 5, 2 — all 3 > 0

Example 3
Input
[5],1
Output
1
Example 4
Input
[-1,-2,-3],2
Output
0
Explanation

All sums negative

Example 5
Input
[1,2,3],2
Output
2
Explanation

[1,2]=3, [2,3]=5

Algorithm Flow

Recommendation Algorithm Flow for Count Windows With Positive Sum
Recommendation Algorithm Flow for Count Windows With Positive Sum

Solution Approach

Compute initial window sum. If sum > 0, count=1 else 0. Slide and update: when sum > 0, increment count.

Best Answers

java
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;
    }
}