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
Any possible combination to add up to target in JavaScript
We are required to write a JavaScript function that takes in an array of unique integers, arr, as the first argument, and target sum as the second argument.
Our function should count the number of all pairs (with repetition allowed) that can add up to the target sum and return that count.
Problem Example
For example, if the input to the function is:
const arr = [1, 2, 3]; const target = 4;
Then the output should be:
7
Output Explanation
The possible combination ways are:
(1, 1, 1, 1) (1, 1, 2) (1, 2, 1) (1, 3) (2, 1, 1) (2, 2) (3, 1)
Solution Using Dynamic Programming
We'll use a recursive approach with memoization to count all possible combinations efficiently:
const arr = [1, 2, 3];
const target = 4;
const sumUpto = (nums = [], target = 1, map = {}) => {
if (target === 0) {
return 1;
}
if (typeof map[target] != "undefined") {
return map[target];
}
let res = 0;
for (let i = 0; i = nums[i]) {
res += sumUpto(nums, target - nums[i], map);
}
}
map[target] = res;
return res;
};
console.log(sumUpto(arr, target));
7
How It Works
The algorithm works as follows:
- Base Case: If target is 0, we found a valid combination (return 1)
- Memoization: If we already calculated combinations for this target, return cached result
- Recursion: For each number in array, if it's ? target, recursively find combinations for (target - number)
- Caching: Store result in map to avoid recalculating
Alternative Iterative Approach
Here's an iterative dynamic programming solution:
const arr = [1, 2, 3];
const target = 4;
const countCombinations = (nums, target) => {
const dp = new Array(target + 1).fill(0);
dp[0] = 1; // One way to make sum 0
for (let i = 1; i = num) {
dp[i] += dp[i - num];
}
}
}
return dp[target];
};
console.log(countCombinations(arr, target));
7
Testing with Different Inputs
// Test case 1
console.log("Array [1,2,3], Target 4:", sumUpto([1, 2, 3], 4));
// Test case 2
console.log("Array [2,3,5], Target 8:", sumUpto([2, 3, 5], 8));
// Test case 3
console.log("Array [1,5], Target 5:", sumUpto([1, 5], 5));
Array [1,2,3], Target 4: 7 Array [2,3,5], Target 8: 5 Array [1,5], Target 5: 6
Conclusion
This problem is solved using dynamic programming with memoization. The recursive solution efficiently counts all possible combinations by breaking down the problem into smaller subproblems and caching results to avoid redundant calculations.
