Skip to content
Advertisement

How to check if any array members can be sum up to the largest of them in JavaScript?

The goal is to create a function that takes an array of numbers as a parameter and checks if the largest of them can be obtained as the sum of any of the other numbers in the array.

One condition is that negative numbers can be a part of the array taken as a parameter.

The problem

The function I came up with sums all the array members except the largest, instead of summing any of them. This is why it fails, as can be seen below

JavaScript

Question

How can I make it work if any array members sum up to the largest?

Advertisement

Answer

After removing the max element from the array, the task now becomes given an array and a target sum(max element) find if there exists any sub-sequence in the array that sums up to the target sum. This problem is identical to the Subset sum problem

The easiest way to solve this is to use the inclusion exclusion principle and solve it in O(2^n) as Mihail’s answer already suggests. There are other ways to solve it more efficiently(have a look at the subset sum problem link)

In the below approach, instead of generating all possible subsets, we only consider the sums of all those subsets. This would save a lot of memory but, the worst time complexity still remains the same which is O(2^n).

JavaScript

Explanation of the approach with an example

JavaScript
Advertisement