Maximum sum of non consecutive elements
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
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.

