Data Structures & AlgorithmsHardCodeforces Div2 C · TCS NQT

Choose any subset of the positions of [4, -2, 7, 3, 9, 1, -5, 8, 2] (possibly empty) so that every two chosen positions are at least 3 apart (indices differ by 3 or more). What is the maximum possible sum?

  1. A. 22
  2. B. 17
  3. C. 21
  4. D. 18

Correct answer: C. 21

dp[i] = max(dp[i−1], a[i] + dp[i−3]): either skip position i or take it, which forces the previous chosen position to be at most i − 3. Allowing neighbours at distance 2 is a different constraint.

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

Exams that ask this topic