MediumArrayQueueSliding WindowHeap (Priority Queue)Ordered SetMonotonic Queue

1 approach, code in every language

Problem description

You are given an integer array nums and an integer limit. Consider any contiguous subarray and look at the difference between its largest and smallest elements.

Return the length of the longest contiguous subarray for which that difference between the maximum and minimum values is at most limit.

Because the maximum and minimum of a window can both change as the window slides, the challenge is to track them efficiently while expanding and contracting.

Example 1

Input: nums = [8,2,4,7], limit = 4

Output: 2

The subarray [2,4] has a max-min difference of 2, which is within the limit, but extending to [2,4,7] gives a difference of 5, so no valid window is longer than 2.

Example 2

Input: nums = [10,1,2,4,7,2], limit = 5

Output: 4

The subarray [2,4,7,2] has maximum 7 and minimum 2, a difference of exactly 5, which satisfies the limit and spans four elements.

Constraints

  • 1 <= nums.length <= 10^5
  • 1 <= nums[i] <= 10^9
  • 0 <= limit <= 10^9

After the pattern

Now solve one you haven't seen.

Steady Pressure Span is our own problem on the technique behind Longest Continuous Subarray With Absolute Diff Less Than or Equal to Limit: a new statement, so there's no answer to remember. Write it in your browser and run it against graded tests.

1,194 problems · 15,062 graded tests · free