VOOZH about

URL: https://www.geeksforgeeks.org/dsa/maximum-subsequence-sum-such-that-no-three-are-consecutive/

⇱ Maximum Sum Without Three Consecutive Elements - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Maximum Sum Without Three Consecutive Elements

Last Updated : 17 Jun, 2026

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.

[Naive Approach] Recursion by Trying All Valid Picks - O(3 ^ n) Time and O(n) Space

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.


Output
5

[Expected Approach] Using Dynamic Programming - O(n) Time and O(1) Space

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 :

  • Handle arrays of size 1 and 2 separately.
  • Initialize the answers for the first three positions.
  • For each remaining element, consider: skipping it, taking it and skipping the previous element and taking it along with the previous element.
  • Store only the last three DP states.

Output
5
Comment
Article Tags: