Longest Subarray With Frequency Limit
You are given an integer array nums and an integer limit. Return the length of the longest contiguous subarray such that the absolute difference between any two elements in the subarray is less than or equal to limit.
In other words, for every pair of indices $i, j$ within the chosen window, $|\text{nums}[i] - \text{nums}[j]| \leq \text{limit}$.
<svg viewBox="0 0 420 60" xmlns="http://www.w3.org/2000/svg" style="max-width:100%;height:auto;"> <text x="10" y="20" font-family="monospace" font-size="12" fill="#666">nums</text> <text x="50" y="42" font-family="monospace" font-size="14" text-anchor="middle" fill="#888">|8</text> <text x="80" y="42" font-family="monospace" font-size="14" text-anchor="middle" fill="#888">13</text> <text x="110" y="42" font-family="monospace" font-size="14" text-anchor="middle" fill="#e11d48">3</text> <text x="140" y="42" font-family="monospace" font-size="14" text-anchor="middle" fill="#e11d48">6</text> <text x="170" y="42" font-family="monospace" font-size="14" text-anchor="middle" fill="#888">2</text> <text x="200" y="42" font-family="monospace" font-size="14" text-anchor="middle" fill="#888">|</text> <line x1="108" y1="48" x2="143" y2="48" stroke="#e11d48" stroke-width="2"/> <line x1="108" y1="48" x2="108" y2="53" stroke="#e11d48" stroke-width="2"/> <line x1="143" y1="48" x2="143" y2="53" stroke="#e11d48" stroke-width="2"/> <text x="125" y="14" font-family="monospace" font-size="10" text-anchor="middle" fill="#e11d48">max-min=3</text> </svg>Examples
Input: [[8,13,3,6,2],3]
Output: 2
Input: [[4,2,2,2,4,4,2,2],0]
Output: 3
Hints
A subarray satisfies the condition iff the difference between its **maximum and minimum** values is within the limit — you only need to track these two extremes, not every pair.
As you extend a window to the right, the range can only stay the same or grow. When it exceeds the limit, shrinking from the left will narrow the range — what values are permanently lost when the left pointer moves?
Think about how to maintain the min and max efficiently as both ends of the window move. An element that is no longer the min or max may still be needed once older, more extreme elements leave the window.
Longest Subarray With Frequency Limit
You are given an integer array `nums` and an integer `limit`. Return the length of the **longest contiguous subarray** such that the absolute difference between **any two elements** in the subarray is less than or equal to `limit`.