Data Structures & AlgorithmsHard

What is the length of the longest contiguous subarray of [4, 6, 5, 8, 9, 7, 10, 3] in which (maximum − minimum) ≤ 2?

  1. A. 2
  2. B. 4
  3. C. 14
  4. D. 3

Correct answer: D. 3

Use a sliding window with a monotonic deque for the max and the min; the window stays valid while max − min ≤ 2. Tightening or loosening the bound, or counting the valid subarrays instead of measuring the longest one, gives a different answer.

More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions

Exams that ask this topic