01 · Question
Counting Subarrays (At-Most-K)
Given an array of sales, count the number of subarrays with at most k bad days (days with fewer than 10 sales).
Key Insight: If a window [l, r] is valid (has <= k bad days), then all subarrays ending at r within this window (i.e., starting from l, l+1, ..., r) are also valid. There are r - l + 1 such subarrays.
02 · Analysis
Maintain the number of bad days in [l,r]. Shrink until it is at most k, then add r-l+1: every start inside the repaired window is valid, and any earlier start is invalid. Return 0 for k < 0, which also makes exactly-k = atMost(k)-atMost(k-1) work for k=0. Time O(n), auxiliary space O(1); the answer can be quadratic in n.