Prepin
Log in

Determine the highest sum of a subsequence where no two elements are adjacent.

Approach / Explanation

This question requires you to determine the highest sum of a subset of numbers in an array, ensuring that the selected elements are not adjacent in the original array. A useful method to tackle this problem is dynamic programming. The core concept involves traversing the array from left to right, where at each step you decide whether to include the current element (while omitting the previous one) or to skip the current element and retain the sum of the previously calculated maximum values. Important aspects to keep in mind while addressing the question: Recognize that this is a dynamic programming challenge. Be aware that you need to loop through the array and modify a 'max sum' variable based on the aforementioned rules. Take into account special scenarios, such as when the array is empty or contains only one element.

Suggested Answer

For example, take the array [5, 5, 10, 100, 10, 5]. We can solve this problem by defining two variables: excl , which represents the maximum sum without including the previous element, and incl , which denotes the maximum sum including the previous element. We start by initializing excl to 0 and incl to the value of the first element in the array. Next, we will iterate through the array beginning with the second element. For each element, we calculate new_excl as the maximum of the previous excl and incl , since we are not including the current element. We then update incl to be excl plus the current element, as we are including it. Afterward, we set excl to new_excl . This way, at each step, we decide whether to exclude the current element and take the maximum of the previous sums, or to include the current element while excluding the previous one. In this scenario, the maximum sum of non-adjacent elements will be 110.

Alternative Answer

Let's examine another example: Consider the array [3, 2, 5, 10, 7]. Just like in the previous example, we begin with excl set to 0 and incl initialized to the first element, which is 3. We then apply the dynamic programming method, calculating the new values for excl and incl for each element. By following this method, the maximum sum without including adjacent elements will be 15. This total comes from adding 3, 5, and 7, which are not next to each other in the original array.

Question Details

Difficulty & Category

Medium

Product

For CandidatesFor RecruitersCompaniesBrowse JobsInterview QuestionsDeep ProfileSkill AssessmentOpportunity Matching
Prepin.ai

© 2026 Prepin LLC · Philadelphia, PA · All rights reserved.