Count Windows With All Positive Elements
Given an integer array and window size k, count how many windows of length k contain only positive numbers (greater than 0). Instead of checking every element in each window, maintain a counter of non-positive elements in the current window.
Start by counting how many elements in the first k elements are non-positive (
<= 0). If this count is zero, the first window qualifies. Then slide through the array. When the leaving element is non-positive, decrement the counter. When the entering element is non-positive, increment it. After each slide, if the counter is zero, all elements in the current window are positive, so increment the result.This counter-based approach is O(n) time and O(1) space because only two elements change per window slide, requiring at most 2 counter adjustments. Without this optimization, checking each window would require O(k) comparisons per window.
The same pattern applies to any binary condition: all even, all odd, all negative, all divisible by a number, etc. The counter tracks how many elements in the current window FAIL the condition, and when it reaches zero, all elements PASS.
This generalizes to any property that can be verified with a "failure counter." The same pattern works for checking if all elements are even, all are negative, all are zeros, etc.
Example Input & Output
Neither [1,-1] nor [-1,2] is all positive
Windows: [1,2,3] and [2,3,4] all positive
Algorithm Flow

Solution Approach
Count non-positive elements in first window. Slide: update count. When count is 0, all are positive.
Best Answers
class Solution {
public int solution(int[] nums, int k) {
if (nums.length<k) return 0;
int np=0;for(int i=0;i<k;i++)if(nums[i]<=0)np++;
int r=np==0?1:0;
for(int i=k;i<nums.length;i++){if(nums[i-k]<=0)np--;if(nums[i]<=0)np++;if(np==0)r++;}
return r;
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
