

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
- Related Questions & Answers
- Maximum size subset with given sum in C++
- Subset Sum Problem
- Maximum subset with bitwise OR equal to k in C++
- Maximum Possible Sum of Products in JavaScript
- Maximum contiguous sum of subarray in JavaScript
- Achieving maximum possible pair sum in JavaScript
- Partition Equal Subset Sum in C++
- Sum of subset differences in C++
- C++ Largest Subset with Sum of Every Pair as Prime
- Maximum subarray sum in circular array using JavaScript
- Python Program for Subset Sum Problem
- Maximum product subset of an array in C++
- Maximum Subarray Sum with One Deletion in C++
- Number of pairs with maximum sum in C++
- Find the sum of maximum difference possible from all subset of a given array in Python
Advertisements