VOOZH about

URL: https://www.geeksforgeeks.org/dsa/count-of-ways-to-obtain-given-sum-from-the-given-array-elements/

⇱ Count of Ways to obtain given Sum from the given Array elements - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Count of Ways to obtain given Sum from the given Array elements

Last Updated : 15 Jul, 2025

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:
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:
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:


Output: 
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: 


Output: 
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: 

  • The original problem reduces to finding the number of ways to find a subset of arr[] that are all positive and the remaining elements as negative, such that their sum is equal to S.
  • Therefore, the problem is to finding no of subsets from the given array having sum (S + totalSum)/2. 

Below is the implementation of the above approach:


Output: 
3

 

Time Complexity: O(n*(sum + S)), where sum denotes the sum of the array 
Auxiliary Space: O(S + sum)


 

Comment
Article Tags: