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

Solution Approach

Count how many subarrays of size k have a positive sum using a sliding window. Maintain the running sum incrementally. For each window, check if the sum is greater than 0.

function countPositiveSumWindows(arr, k) {
  var sum = 0, count = 0;
  for (var i = 0; i < k; i++) sum += arr[i];
  if (sum > 0) count++;
  for (var i = k; i < arr.length; i++) {
    sum = sum - arr[i - k] + arr[i];
    if (sum > 0) count++;
  }
  return count;
}

The sliding window updates the sum by subtracting the outgoing element and adding the incoming one, keeping the computation O(1) per position.

Time O(n), Space O(1).

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