Pattern - At Most K

Counting subarrays with at most k of something.

Problem: Count subarrays with at most kk distinct elements.

Approach: For each right endpoint, find smallest valid left. Count: rightleft+1right - left + 1 subarrays ending at right.

Trick: "Exactly kk" = "At most kk" - "At most k1k-1". Counting exactly kk directly is complex; subtracting two simpler counts avoids edge cases.