Data Structures & AlgorithmsHardCodeforces Div2 D · TCS NQT

In [3, 4, 9, 5, 6, 2, 1, 7, 8], what is the length of the longest subsequence (keeping the order) in which every pair of consecutive chosen values differs by exactly 1?

  1. A. 6
  2. B. 2
  3. C. 9
  4. D. 3

Correct answer: A. 6

dp[i] = 1 + max dp[j] over earlier j with |a[i] − a[j]| = 1; 3, 4, 5, 6, 7, 8 gives 6. Requiring the chosen values to be adjacent in the array gives only 2, 9 is the array length, and 3 is a short chain such as 3, 4, 5.

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

Exams that ask this topic