Maintain a contiguous subarray that grows and shrinks as you scan. Keep it valid, track the best. One pass, O(n).
What Is It?
You maintain a window [l, r] over the array. Expand r to include new elements. When the window violates your constraint, shrink from the left by advancing l. At every step, your window is the best valid window ending at r, so you update your answer.
The beauty is that both l and r only move forward. Each element is added once and removed at most once. Total work: O(n), not O(n²).
Think of it like a caterpillar inching across the array — the front stretches forward, the back catches up when things get too long.