Maximum sum of non consecutive elements
Data Structures & Algorithms practice on Codemia
Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.
Introduction
The problem of finding the maximum sum of non-consecutive elements in an array is a classic example of a dynamic programming problem. It asks you to identify the largest possible sum you can get from an array or a list of numbers without picking two adjacent elements. This problem often serves as a gateway to understanding more complex dynamic programming techniques.
Problem Definition
Given an array of integers, the task is to find the maximum sum possible by selecting non-consecutive elements from this array.
Example
Consider the array . You want to find the maximum sum you can achieve by selecting non-consecutive numbers.
- If you select , the next eligible elements are , , and .
- If you select , the next eligible elements are and .
- If you select , the next eligible elements are .
• Optimal selection in this case would be , yielding a sum of . • Alternatively, also yields a sum of . • However, the most optimal solution is which provides a sum of .
Dynamic Programming Solution
The key idea here is to build up a solution incrementally using dynamic programming. We will maintain an array where will store the maximum sum we can get including the element such that no two elements are adjacent.
Recursive Relationship
The recursive relationship can be defined as:
Where: • is the maximum sum without including the element. • is the maximum sum including the element and not including the consecutive element.
Base Cases
• : If there is only one element, the maximum sum is that element itself. • : For two elements, select the larger of the two.
Implementation
Here is a Python implementation of the above logic:
• House Robber Problem: Finding the maximum amount a robber can rob without alerting police when houses are in a straight line. • Stock Market Analysis: To find the largest sum of gains from stocks in a non-consecutive timeframe.
Related reading
- Maximum Sum SubArray
- Maximum sum sublist?
- maximum sum subrectangle in a sparse matrix
- Maximum weighted bipartite matching, constraint ordering of each graph is preserved
- Maximum xor among all subsets of an array
- MD5 vs CRC32 Which one's better for common use?
- Meaning of the ⊥ symbol in distributed algorithm context
- Meaning of the terms O1 space and without using extra space

DSA Fundamentals
Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.
View the courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Data Structures & Algorithms practice on Codemia
Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.