Longest Continuous Subarray With Absolute Diff

Medium · Stack & Strings · Array · Queue · Sliding Window · Monotonic Queue · Heap (Priority Queue)

Problem

You are given an integer array nums and an integer limit.

Return the length of the longest non-empty contiguous subarray in which the absolute difference between any two values is at most limit. Put another way, the subarray’s maximum minus its minimum must be <= limit.

Examples

Input: nums = [3,6,5,9,4,4], limit = 3
Output: 3

[3,6,5] has spread 6 - 3 = 3. [6,5,9] fails because 9 - 5 = 4, and no window of 4 fits.

Input: nums = [7,7,7,1], limit = 0
Output: 3

With limit 0 every value must be equal; the first three 7s are the longest such run.

Input: nums = [10,1,2,3,20], limit = 5
Output: 3

[1,2,3] has spread 2; any window touching 10 or 20 is wider than 5.

Constraints

Approaches

Follow-up

What if you had to count every subarray with spread at most limit, not just find the longest? The same window gives it: at each right end, all right - left + 1 starts fit. See the first use case.

Related problems

Start free on Cariara · Coding problems · System design studio

Starting Python
No results yet.

          
↑↓ move ↵ open esc close

Labs

Loading labs…

Run with your own input

Starting Python

Loading Python…