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
Ways to get to a specific sum in JavaScript
Problem
We are required to write a JavaScript function that takes in an array of integers, arr, as the first argument and a single integer, target, as the second argument.
For each integer in the array, our function can either assign '+' or '-' to it. Our function should find out how many ways in total exist to assign '+', '-' to make the sum of integers of the array equal to the target sum.
For example, if the input to the function is:
const arr = [1, 1, 1, 1, 1]; const target = 3;
Then the output should be:
5
Output Explanation
The 5 ways to achieve the target sum are:
-1+1+1+1+1 = 3 +1-1+1+1+1 = 3 +1+1-1+1+1 = 3 +1+1+1-1+1 = 3 +1+1+1+1-1 = 3
Solution Using Dynamic Programming
The solution uses dynamic programming with memoization to avoid recalculating the same subproblems. The algorithm works recursively by considering two choices for each element: adding it or subtracting it.
const arr = [1, 1, 1, 1, 1];
const target = 3;
const waysToSum = (arr = [], target = 1) => {
const map = {};
const find = (arr, target, i) => {
let val = i + '->' + target;
// Check if already computed
if (map[val] !== undefined) {
return map[val];
}
// Base case: reached first element
if (i === 0) {
if (target === 0 && arr[0] === 0) {
return 2; // Both +0 and -0 work
}
return arr[0] === target || arr[0] === -target ? 1 : 0;
}
// Recursive case: add or subtract current element
map[val] = find(arr, target + arr[i], i - 1) + find(arr, target - arr[i], i - 1);
return map[val];
};
return find(arr, target, arr.length - 1);
};
console.log(waysToSum(arr, target));
Output
5
How It Works
The algorithm uses a recursive approach with memoization:
- Base case: When we reach the first element (index 0), we check if it can equal the target with either + or - sign
- Recursive case: For each element, we calculate ways by adding it and ways by subtracting it
- Memoization: We store results using a key format "index->target" to avoid recalculation
Alternative Example
const arr2 = [1, 0, 1];
const target2 = 0;
console.log("Array:", arr2);
console.log("Target:", target2);
console.log("Ways to achieve target:", waysToSum(arr2, target2));
Array: [ 1, 0, 1 ] Target: 0 Ways to achieve target: 4
Conclusion
This dynamic programming approach efficiently counts all possible ways to assign + or - signs to array elements to reach a target sum. The memoization technique ensures optimal performance by avoiding redundant calculations.
