Count Windows With All Positives
Given an array of integers and a window size k, count how many subarrays of length k have a majority of positive elements (more than half the elements are greater than 0). Return the count of such windows.
For example, in [1, -2, 3, 4, -1] with k=3, windows: [1,-2,3] has 2 positives (majority), [-2,3,4] has 2 positives (majority), [3,4,-1] has 2 positives (majority). Return 3. With k=2, [1,-2] has 1 positive (not majority), [-2,3] has 1, [3,4] has 2, [-1] is invalid. Return 1.
This problem teaches majority threshold checking within sliding windows. A majority requires more than k/2 elements satisfying the condition. The sliding window maintains a count of positives incrementally.
The solution initializes a positive count in the first window. Slide: adjust the count when the outgoing or incoming element is positive. After each slide, check if the count exceeds k/2.
Edge cases include k larger than the array (return 0), an empty array (return 0), and k=1 (a single positive element has majority 1 > 0.5).
Example Input & Output
[5,6] and [6,7] both all positive.
No positive elements.
Only [2,3] is all positive.
Empty array.
Windows [1,2,3] and [2,3,4] are all positive.
Algorithm Flow

Solution Approach
Use a sliding window to maintain the count of positive numbers incrementally and check majority.
Count positives in the first window. Slide: decrement when a positive leaves, increment when a positive enters. Check majority after each slide by comparing the positive count to k/2.
Time complexity is O(n), space complexity is O(1).
Best Answers
def solution(nums, k):
if len(nums)<k: return 0
neg=sum(1 for i in range(k) if nums[i]<=0)
res=1 if neg==0 else 0
for i in range(k,len(nums)):
if nums[i-k]<=0: neg-=1
if nums[i]<=0: neg+=1
if neg==0: res+=1
return resComments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
