Count Decreasing Windows
Given an array of integers and a window size k, count how many subarrays of length k are strictly decreasing (each element is less than the previous one). Return the count of such windows.
For example, in [5, 4, 3, 2, 1] with k=3, all windows are decreasing: [5,4,3], [4,3,2], [3,2,1] — return 3. In [5, 4, 6, 3] with k=3, [5,4,6] is not decreasing (6>4), [4,6,3] is not decreasing — return 0.
This problem teaches sliding window with monotonic condition checking. Instead of checking each window from scratch, you can track whether the current window is decreasing incrementally.
The solution tracks the number of decreasing adjacent pairs within the current window. A window of size k is strictly decreasing if it has exactly k-1 decreasing pairs (each adjacent pair is decreasing).
Edge cases include k larger than the array (return 0), k=1 (single-element windows are trivially decreasing), and equal adjacent elements (they are not strictly decreasing).
Example Input & Output
Single element trivially decreasing
Empty array
Only [5,3,1] is decreasing
All increasing, none decreasing
[5,4,3],[4,3,2],[3,2,1] all decreasing
Algorithm Flow
Solution Approach
Track decreasing adjacent pairs within the sliding window.
Count decreasing pairs in the first window. Slide: when the pair leaving the window was decreasing, decrement; when the new pair entering is decreasing, increment. A window is valid when decPairs equals k-1.
Time complexity is O(n), space complexity is O(1).
Best Answers
class Solution {
public int solution(int[] nums, int k) {
if(nums.length<k)return 0;
int v=0;for(int i=1;i<k;i++){if(nums[i]>=nums[i-1])v++;}
int r=v==0?1:0;
for(int i=k;i<nums.length;i++){
if(nums[i-k]<=nums[i-k+1])v--;
if(nums[i]>=nums[i-1])v++;
if(v==0)r++;
}return r;
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
