![]() |
VOOZH | about |
Given an array arr[], consisting of N non-negative integers and an integer S, the task is to find the number of ways to obtain the sum S by adding or subtracting array elements.
Note: All the array elements need to be involved in generating the sum.
Examples:
Input: arr[] = {1, 1, 1, 1, 1}, S = 3
Output: 5
Explanation:
Following are the possible ways to obtain the sum S:
- -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
Input: arr[] = {1, 2, 3, 4, 5}, S = 3
Output: 3
Explanation:
Following are the possible ways to obtain the sum S:
- -1 -2 -3 + 4 + 5 = 3
- -1 + 2 + 3 + 4 - 5 = 3
- 1 - 2 + 3 - 4 + 5 = 3
Recursive Approach: It can be observed that each array element can either be added or subtracted to obtain sum. Therefore, for each array element, recursively check for both the possibilities and increase count when sum S is obtained after reaching the end of the array.
Below is the implementation of the above approach:
3
Time Complexity: O(2N)
Auxiliary Space: O(1)
Dynamic Programming Approach: The above recursive approach can be optimized by using Memoization.
Below is the implementation of the above approach:
3
Time Complexity: O(N * S)
Auxiliary Space: O(N * S)
Knapsack Approach: The idea is to implement the 0/1 Knapsack problem. Follow the steps below:
Below is the implementation of the above approach:
3
Time Complexity: O(n*(sum + S)), where sum denotes the sum of the array
Auxiliary Space: O(S + sum)