AlgoMaster Logo

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

Ashish

Ashish Pratap Singh

medium

Problem Description

Solve it on LeetCode

Approaches

1. Brute Force

Intuition:

The simplest way to solve this problem is by checking every possible subarray and verifying if it meets the condition, i.e., its maximum and minimum difference is less than or equal to the given limit. This involves calculating the max and min for all subarrays which can be computationally expensive but forms the foundation of understanding the problem.

Steps:

  1. Iterate over each starting index of a subarray.
  2. For each starting index, iterate over each possible ending index, maintaining the current maximum and minimum in the subarray.
  3. If at any point the difference between the maximum and minimum exceeds the limit, move to the next starting index.
  4. Keep track of the length of the longest valid subarray found.

Code:

2. Optimized Sliding Window with Two Deques

Intuition:

The brute force solution is inefficient due to redundant checks for the max and min. A more optimal solution can maintain a sliding window of elements, while keeping the current maximum and minimum within this window through deques. As the sliding window expands, the deques are used to update and maintain the max and min efficiently.

Steps:

  1. Use two deques to store the indices of the elements. One deque stores indices in decreasing order to get the minimum, and another in increasing order for the maximum.
  2. Initialize your window's start pointer left to zero.
  3. Expand the window by moving the right pointer and update deques.
  4. Check the condition by comparing the max and min using the front of both deques.
  5. If the condition is not met (max - min > limit), increment the left pointer.
  6. Calculate the maximum length of the window that satisfies the condition.
  7. Return the result.

Code: