Data Structures & AlgorithmsHard

Choose a subsequence (elements need not be adjacent, but keep their original order) of [1, 9, 3, 4, 8, 2, 10, 5] of largest size such that max − min ≤ 2. What is that largest size?

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

Correct answer: A. 3

Sorting the values turns the condition into a window over sorted values, so the best subsequence is all values lying in a window of width 2. Restricting to contiguous subarrays loses the scattered values, and a wider bound overcounts.

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

Exams that ask this topic