Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Finding all possible combined (plus and minus) sums of n arguments JavaScript
We need to write a JavaScript function that takes any number of arguments (all numbers) and finds the sum closest to zero from all possible combinations of addition and subtraction.
For example, with arguments 1, 2, 3, the possible combinations are:
1 + 2 + 3 = 6 1 - 2 - 3 = -4 1 + 2 - 3 = 0 1 - 2 + 3 = 2
The function should return the sum closest to 0, which in this case is 0.
Algorithm Approach
We use a Set to store all possible absolute sums. For each new number, we calculate both addition and subtraction with existing sums, then keep track of the minimum absolute value.
Implementation
const findSmallestPositive = (...arr) => {
let set = new Set([Math.abs(arr[0])]);
for (let i = 1; i < arr.length; i++) {
const secondSet = new Set();
for (let d of Array.from(set)) {
secondSet.add(Math.abs(d + arr[i]));
secondSet.add(Math.abs(d - arr[i]));
}
set = secondSet;
}
return Math.min(...Array.from(set));
};
console.log(findSmallestPositive(5, 3));
console.log(findSmallestPositive(1, 2, 3));
console.log(findSmallestPositive(1, 2, 3, 5));
2 0 1
How It Works
The algorithm works by:
- Starting with the absolute value of the first number in a Set
- For each subsequent number, creating all possible sums by adding and subtracting it from existing values
- Taking absolute values to find the closest to zero
- Returning the minimum value from the final Set
Step-by-Step Example
For inputs (1, 2, 3):
// Step 1: Start with first number
let set = new Set([1]); // {1}
// Step 2: Add/subtract second number (2)
// |1 + 2| = 3, |1 - 2| = 1
set = new Set([3, 1]); // {3, 1}
// Step 3: Add/subtract third number (3)
// |3 + 3| = 6, |3 - 3| = 0, |1 + 3| = 4, |1 - 3| = 2
set = new Set([6, 0, 4, 2]); // {6, 0, 4, 2}
// Result: Math.min(6, 0, 4, 2) = 0
console.log("Final result:", Math.min(6, 0, 4, 2));
Final result: 0
Conclusion
This algorithm efficiently finds the sum closest to zero by exploring all possible addition and subtraction combinations using Sets to avoid duplicates. The time complexity is O(n × 2^n) where n is the number of arguments.
