Subset with maximum sum in JavaScript

In JavaScript, finding the subset of non-adjacent elements with maximum sum is a classic dynamic programming problem. We need to decide whether to include each element or skip it, ensuring no two adjacent elements are selected.

The key insight is that for each element, we have two choices: include it (and skip the previous element) or exclude it (and take the maximum sum up to the previous element).

Problem Statement

Given an array of integers, find the subset of non-adjacent elements that produces the maximum sum. Adjacent elements cannot be selected together.

For example, with the array [3, 5, 7, 8, 10], the optimal subset is [3, 7, 10] with sum 20.

Example

const arr = [3, 5, 7, 8, 10];

const maxSubsetSum = (arr = []) => {
    let min = -Infinity;
    
    const helper = (arr, ind) => {
        if (ind < 0) {
            return min;
        }
        
        let inc = helper(arr, ind - 2);
        let notInc = helper(arr, ind - 1);
        inc = inc == min ? arr[ind] : Math.max(arr[ind], arr[ind] + inc);
        
        return Math.max(inc, notInc);
    };
    
    return helper(arr, arr.length - 1);
};

console.log(maxSubsetSum(arr));
20

How It Works

The recursive solution works by considering two scenarios at each position:

  • Include current element: Add current element to the maximum sum from two positions back
  • Exclude current element: Take the maximum sum from the previous position

The algorithm chooses the better option at each step, ensuring optimal substructure.

Optimized Dynamic Programming Approach

const maxSubsetSumDP = (arr) => {
    if (arr.length === 0) return 0;
    if (arr.length === 1) return arr[0];
    
    let incl = arr[0];  // Maximum sum including previous element
    let excl = 0;       // Maximum sum excluding previous element
    
    for (let i = 1; i < arr.length; i++) {
        let newExcl = Math.max(incl, excl);
        incl = excl + arr[i];
        excl = newExcl;
    }
    
    return Math.max(incl, excl);
};

const testArray = [3, 5, 7, 8, 10];
console.log("Recursive approach:", maxSubsetSum(testArray));
console.log("DP approach:", maxSubsetSumDP(testArray));
Recursive approach: 20
DP approach: 20

Comparison

Approach Time Complexity Space Complexity Suitable for
Recursive O(2^n) O(n) Small arrays
Dynamic Programming O(n) O(1) Large arrays

Conclusion

The dynamic programming approach is more efficient for finding maximum subset sum of non-adjacent elements. It processes each element once and maintains optimal solutions using constant space.

Updated on: 2026-03-15T23:19:00+05:30

379 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements