Data Structures & AlgorithmsVery hard
When choosing non-adjacent positions to maximise a sum, why does the DP keep two states per position?
- 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.
- B. One state stores the sum and the other stores the length.
- C. Both states store the maximum element.
- 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.
Practise more Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questionsArrays, Strings, Linked Lists, Stacks, Queues and Hashing: notes and key points
More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions
- Why does the lexicographically largest subsequence after deleting k digits come from a greedy stack?
- In a sliding window tracking the maximum number of vowels among windows of fixed length 3, why is O(1) update per step possible?
- Why does a circular window of length 3 require index arithmetic modulo n?
- Why is the number of Dyck-word stack sequences with n pushes and n pops equal to a Catalan number?
- A deque-based minimum of each sliding window runs in linear time because:
- How many ways are there to make 15 using coins of values 1, 2, 5 and 10, where the order of coins does not matter (so 5+5+5 and 5+10 are…