![]() |
VOOZH | about |
Given an array arr[] of positive integers, find the maximum possible sum of a subsequence such that no three selected elements are consecutive in the original array.
Examples :
Input: arr[] = [1, 2, 3]
Output: 5
Explanation: We can't take three of them, so answer is 2 + 3 = 5.Input: arr[] = [3000, 2000, 1000, 3, 10]
Output: 5013
Explanation: 3000 + 2000 + 3 + 10 = 5013.
Table of Content
At each index, we make one of three choices -
- Skip It
- Pick only Current
- Pick it along with the previous element.
Each choice ensures no three consecutive elements are ever selected. We return the maximum across all three choices.
5
Since the same subproblems repeat across branches, the time complexity grows exponentially. Therefore we use Dynamic programming to solve this problem.
At each element, we have three choices: skip it, take it while skipping the previous element, or take it along with the previous element while skipping the one before them. The maximum sum at each position is the best of these choices. Since only the last three states are needed, the solution can be optimized to use constant extra space.
Step :
5