MediumArrayQueueSliding WindowHeap (Priority Queue)Ordered SetMonotonic Queue

Longest Continuous Subarray With Absolute Diff Less Than or Equal to Limit

LeetCode
1 approach, code in all languages

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
You've got the patterns

Patterns get you through the screen. Shipping gets you hired.

FDE Coach is a cohort-based program in frontend, backend, AWS, and AI where you build real products and get referred to 200+ hiring partners. The free live workshop is the fastest way to see how we teach.

750+ engineers trained · frontend, backend, AWS & AI

August 15 · 0d left
Enroll Now