Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Subset with maximum sum in JavaScript
We are required to write a JavaScript function that takes in an array of integers. Our function is required find the subset of non−adjacent elements with the maximum sum.
And finally, the function should calculate and return the sum of that subset.
For example −
If the input array is −
const arr = [3, 5, 7, 8, 10];
Then the output should be 20 because the non−adjacent subset of numbers will be 3, 7 and 10.
Example
The code for this will be −
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));
Output
And the output in the console will be −
20
Advertisements