Data Structures & AlgorithmsVery hard

When choosing non-adjacent positions to maximise a sum, why does the DP keep two states per position?

  1. A. One state for the best sum that uses the current position and one for the best that does not, since using it forbids its neighbour.
  2. B. One state stores the sum and the other stores the length.
  3. C. Both states store the maximum element.
  4. D. The second state is needed only when all values are negative.

Correct answer: A. One state for the best sum that uses the current position and one for the best that does not, since using it forbids its neighbour.

Taking position i blocks i−1, while skipping it allows i−1, so the two states capture both possibilities. This is the standard take-or-skip recurrence.

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

Exams that ask this topic