Count of Ways to obtain given Sum from the given Array elements
Last Updated :
14 Jun, 2021
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:
C++
// C++ program to implement
// the above approach
#include<bits/stdc++.h>
using namespace std;
// Function to count the number of ways
int dfs(int nums[], int S, int curr_sum,
int index, int n)
{
// Base Case: Reached the
// end of the array
if (index == n)
{
// Sum is equal to the
// required sum
if (S == curr_sum)
return 1;
else
return 0;
}
// Recursively check if required sum
// can be obtained by adding current
// element or by subtracting the
// current index element
return dfs(nums, S, curr_sum + nums[index],
index + 1, n) +
dfs(nums, S, curr_sum - nums[index],
index + 1, n);
}
// Function to call dfs() to
// calculate the number of ways
int findWays(int nums[], int S, int n)
{
return dfs(nums, S, 0, 0, n);
}
// Driver Code
int main()
{
int S = 3;
int arr[] = { 1, 2, 3, 4, 5 };
int n = sizeof(arr) / sizeof(arr[0]);
int answer = findWays(arr, S, n);
cout << (answer);
return 0;
}
// This code is contributed by chitranayal
Java
// Java Program to implement
// the above approach
import java.io.*;
class GFG {
// Function to call dfs() to
// calculate the number of ways
static int findWays(int[] nums, int S)
{
return dfs(nums, S, 0, 0);
}
// Function to count the number of ways
static int dfs(int[] nums, int S,
int curr_sum, int index)
{
// Base Case: Reached the
// end of the array
if (index == nums.length) {
// Sum is equal to the
// required sum
if (S == curr_sum)
return 1;
else
return 0;
}
// Recursively check if required sum
// can be obtained by adding current
// element or by subtracting the
// current index element
return dfs(nums, S, curr_sum + nums[index],
index + 1)
+ dfs(nums, S, curr_sum - nums[index],
index + 1);
}
// Driver Code
public static void main(String[] args)
{
int S = 3;
int[] arr = new int[] { 1, 2, 3, 4, 5 };
int answer = findWays(arr, S);
System.out.println(answer);
}
}
Python3
# Python3 program to implement
# the above approach
# Function to count the number of ways
def dfs(nums, S, curr_sum, index):
# Base Case: Reached the
# end of the array
if (index == len(nums)):
# Sum is equal to the
# required sum
if (S == curr_sum):
return 1;
else:
return 0;
# Recursively check if required sum
# can be obtained by adding current
# element or by subtracting the
# current index element
return (dfs(nums, S, curr_sum + nums[index],
index + 1) +
dfs(nums, S, curr_sum - nums[index],
index + 1));
# Function to call dfs() to
# calculate the number of ways
def findWays(nums, S):
return dfs(nums, S, 0, 0);
# Driver Code
if __name__ == '__main__':
S = 3;
arr = [1, 2, 3, 4, 5];
answer = findWays(arr, S);
print(answer);
# This code is contributed by amal kumar choubey
C#
// C# Program to implement
// the above approach
using System;
class GFG{
// Function to call dfs() to
// calculate the number of ways
static int findWays(int[] nums, int S)
{
return dfs(nums, S, 0, 0);
}
// Function to count the number of ways
static int dfs(int[] nums, int S,
int curr_sum, int index)
{
// Base Case: Reached the
// end of the array
if (index == nums.Length)
{
// Sum is equal to the
// required sum
if (S == curr_sum)
return 1;
else
return 0;
}
// Recursively check if required sum
// can be obtained by adding current
// element or by subtracting the
// current index element
return dfs(nums, S, curr_sum +
nums[index], index + 1) +
dfs(nums, S, curr_sum -
nums[index], index + 1);
}
// Driver Code
public static void Main(String[] args)
{
int S = 3;
int[] arr = new int[] { 1, 2, 3, 4, 5 };
int answer = findWays(arr, S);
Console.WriteLine(answer);
}
}
// This code is contributed by Rajput-Ji
JavaScript
<script>
// Javascript Program to implement
// the above approach
// Function to call dfs() to
// calculate the number of ways
function findWays(nums, S)
{
return dfs(nums, S, 0, 0);
}
// Function to count the number of ways
function dfs(nums, S, curr_sum, index)
{
// Base Case: Reached the
// end of the array
if (index == nums.length)
{
// Sum is equal to the
// required sum
if (S == curr_sum)
return 1;
else
return 0;
}
// Recursively check if required sum
// can be obtained by adding current
// element or by subtracting the
// current index element
return dfs(nums, S, curr_sum +
nums[index], index + 1) +
dfs(nums, S, curr_sum -
nums[index], index + 1);
}
let S = 3;
let arr = [ 1, 2, 3, 4, 5 ];
let answer = findWays(arr, S);
document.write(answer);
</script>
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:
C++
// C++ Program to implement
// the above approach
#include <bits/stdc++.h>
using namespace std;
// Function to perform the DFS to calculate the
// number of ways
int dfs(vector<vector<int>> memo, int nums[], int S,
int curr_sum, int index, int sum, int N)
{
// Base case: Reached the end of array
if (index == N) {
// If current sum is obtained
if (S == curr_sum)
return 1;
// Otherwise
else
return 0;
}
// If previously calculated
// subproblem occurred
if (memo[index][curr_sum + sum]
!= INT_MIN) {
return memo[index][curr_sum + sum];
}
// Check if the required sum can
// be obtained by adding current
// element or by subtracting the
// current index element
int ans = dfs(memo, nums, index + 1,
curr_sum + nums[index], S, sum, N)
+ dfs(memo, nums, index + 1,
curr_sum - nums[index], S, sum, N);
// Store the count of ways
memo[index][curr_sum + sum] = ans;
return ans;
}
// Function to call dfs
// to calculate the number of ways
int findWays(int nums[], int S, int N)
{
int sum = 0;
// Iterate till the length of array
for (int i = 0; i < N; i++)
sum += nums[i];
// Initialize the memorization table
vector<vector<int>> memo(N + 1, vector<int> (2 * sum + 1, INT_MIN));
return dfs(memo, nums, S, 0, 0, sum, N);
}
// Driver code
int main()
{
int S = 3;
int arr[] ={ 1, 2, 3, 4, 5 };
int N = sizeof(arr) / sizeof(arr[0]);
int answer = findWays(arr, S, N);
cout << answer << endl;
return 0;
}
// This code is contributed by divyesh072019
Java
// Java Program to implement
// the above approach
import java.io.*;
import java.util.*;
class GFG {
// Function to call dfs
// to calculate the number of ways
static int findWays(int[] nums, int S)
{
int sum = 0;
// Iterate till the length of array
for (int i = 0; i < nums.length; i++)
sum += nums[i];
// Initialize the memorization table
int[][] memo
= new int[nums.length + 1][2 * sum + 1];
for (int[] m : memo) {
Arrays.fill(m, Integer.MIN_VALUE);
}
return dfs(memo, nums, S, 0, 0, sum);
}
// Function to perform the DFS to calculate the
// number of ways
static int dfs(int[][] memo, int[] nums, int S,
int curr_sum, int index, int sum)
{
// Base case: Reached the end of array
if (index == nums.length) {
// If current sum is obtained
if (S == curr_sum)
return 1;
// Otherwise
else
return 0;
}
// If previously calculated
// subproblem occurred
if (memo[index][curr_sum + sum]
!= Integer.MIN_VALUE) {
return memo[index][curr_sum + sum];
}
// Check if the required sum can
// be obtained by adding current
// element or by subtracting the
// current index element
int ans = dfs(memo, nums, index + 1,
curr_sum + nums[index], S, sum)
+ dfs(memo, nums, index + 1,
curr_sum - nums[index], S, sum);
// Store the count of ways
memo[index][curr_sum + sum] = ans;
return ans;
}
// Driver Code
public static void main(String[] args)
{
int S = 3;
int[] arr = new int[] { 1, 2, 3, 4, 5 };
int answer = findWays(arr, S);
System.out.println(answer);
}
}
Python3
# Python3 program to implement
# the above approach
import sys
# Function to call dfs to
# calculate the number of ways
def findWays(nums, S):
sum = 0
# Iterate till the length of array
for i in range(len(nums)):
sum += nums[i]
# Initialize the memorization table
memo = [[-sys.maxsize - 1 for i in range(2 * sum + 1)]
for j in range(len(nums) + 1)]
return dfs(memo, nums, S, 0, 0, sum)
# Function to perform the DFS to calculate the
# number of ways
def dfs(memo, nums, S, curr_sum, index, sum):
# Base case: Reached the end of array
if (index == len(nums)):
# If current sum is obtained
if (S == curr_sum):
return 1
# Otherwise
else:
return 0
# If previously calculated
# subproblem occurred
if (memo[index][curr_sum + sum] != -sys.maxsize - 1):
return memo[index][curr_sum + sum]
# Check if the required sum can
# be obtained by adding current
# element or by subtracting the
# current index element
ans = (dfs(memo, nums, index + 1,
curr_sum + nums[index], S, sum) +
dfs(memo, nums, index + 1,
curr_sum - nums[index], S, sum))
# Store the count of ways
memo[index][curr_sum + sum] = ans
return ans
# Driver Code
if __name__ == '__main__':
S = 3
arr = [ 1, 2, 3, 4, 5 ]
answer = findWays(arr, S)
print(answer)
# This code is contributed by bgangwar59
C#
// C# program to implement
// the above approach
using System;
class GFG{
// Function to call dfs
// to calculate the number of ways
static int findWays(int[] nums, int S)
{
int sum = 0;
// Iterate till the length of array
for(int i = 0; i < nums.Length; i++)
sum += nums[i];
// Initialize the memorization table
int[,] memo = new int[nums.Length + 1,
2 * sum + 1];
for(int i = 0; i < memo.GetLength(0); i++)
{
for(int j = 0; j < memo.GetLength(1); j++)
{
memo[i, j] = int.MinValue;
}
}
return dfs(memo, nums, S, 0, 0, sum);
}
// Function to perform the DFS to calculate the
// number of ways
static int dfs(int[,] memo, int[] nums, int S,
int curr_sum, int index, int sum)
{
// Base case: Reached the end of array
if (index == nums.Length)
{
// If current sum is obtained
if (S == curr_sum)
return 1;
// Otherwise
else
return 0;
}
// If previously calculated
// subproblem occurred
if (memo[index, curr_sum + sum] != int.MinValue)
{
return memo[index, curr_sum + sum];
}
// Check if the required sum can
// be obtained by adding current
// element or by subtracting the
// current index element
int ans = dfs(memo, nums, index + 1,
curr_sum + nums[index], S, sum) +
dfs(memo, nums, index + 1,
curr_sum - nums[index], S, sum);
// Store the count of ways
memo[index, curr_sum + sum] = ans;
return ans;
}
// Driver Code
public static void Main(String[] args)
{
int S = 3;
int[] arr = new int[] { 1, 2, 3, 4, 5 };
int answer = findWays(arr, S);
Console.WriteLine(answer);
}
}
// This code is contributed by Amit Katiyar
JavaScript
<script>
// Javascript program to implement
// the above approach
// Function to call dfs
// to calculate the number of ways
function findWays(nums, S)
{
let sum = 0;
// Iterate till the length of array
for(let i = 0; i < nums.length; i++)
sum += nums[i];
// Initialize the memorization table
let memo = new Array([nums.length + 1][2 * sum + 1]);
for(let i = 0; i < nums.length + 1; i++)
{
memo[i] = new Array(2 * sum + 1);
for(let j = 0; j < 2 * sum + 1; j++)
{
memo[i][j] = Number.MIN_VALUE;
}
}
return dfs(memo, nums, S, 0, 0, sum);
}
// Function to perform the DFS to calculate
// the number of ways
function dfs(memo, nums, S, curr_sum, index, sum)
{
// Base case: Reached the end of array
if (index == nums.length)
{
// If current sum is obtained
if (S == curr_sum)
return 1;
// Otherwise
else
return 0;
}
// If previously calculated
// subproblem occurred
if (memo[index][curr_sum + sum] !=
Number.MIN_VALUE)
{
return memo[index][curr_sum + sum];
}
// Check if the required sum can
// be obtained by adding current
// element or by subtracting the
// current index element
let ans = dfs(memo, nums, index + 1,
curr_sum + nums[index], S, sum) +
dfs(memo, nums, index + 1,
curr_sum - nums[index], S, sum);
// Store the count of ways
memo[index][curr_sum + sum] = ans;
return ans;
}
// Driver Code
let S = 3;
let arr = [ 1, 2, 3, 4, 5 ];
let answer = findWays(arr, S);
document.write(answer);
// This code is contributed by avanitrachhadiya2155
</script>
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:
C++
// C++ program to implement
// the above approach
#include <bits/stdc++.h>
using namespace std;
// Function to call dfs
// to calculate the number of ways
int knapSack(int nums[], int S, int n)
{
int sum = 0;
for(int i = 0; i < n; i++)
sum += nums[i];
// If target + sum is odd or
// S exceeds sum
if (sum < S || -sum > -S ||
(S + sum) % 2 == 1)
// No sultion exists
return 0;
int dp[(S + sum) / 2 + 1];
for(int i = 0; i <= (S + sum) / 2; i++)
dp[i] = 0;
dp[0] = 1;
for(int j = 0; j < n; j++)
{
for(int i = (S + sum) / 2;
i >= nums[j]; i--)
{
dp[i] += dp[i - nums[j]];
}
}
// Return the answer
return dp[(S + sum) / 2];
}
// Driver Code
int main()
{
int S = 3;
int arr[] = { 1, 2, 3, 4, 5 };
int answer = knapSack(arr, S, 5);
cout << answer << endl;
}
// This code is contributed by amal kumar choubey
Java
// Java Program to implement
// the above approach
import java.io.*;
class GFG {
// Function to call dfs
// to calculate the number of ways
static int knapSack(int[] nums, int S)
{
int sum = 0;
for (int i : nums)
sum += i;
// If target + sum is odd or S exceeds sum
if (sum < S || -sum > -S || (S + sum) % 2 == 1)
// No sultion exists
return 0;
int[] dp = new int[(S + sum) / 2 + 1];
dp[0] = 1;
for (int num : nums) {
for (int i = dp.length - 1; i >= num; i--) {
dp[i] += dp[i - num];
}
}
// Return the answer
return dp[dp.length - 1];
}
// Driver Code
public static void main(String[] args)
{
int S = 3;
int[] arr = new int[] { 1, 2, 3, 4, 5 };
int answer = knapSack(arr, S);
System.out.println(answer);
}
}
Python3
# Python3 Program to implement
# the above approach
# Function to call dfs
# to calculate the number of ways
def knapSack(nums, S):
sum = 0;
for i in range(len(nums)):
sum += nums[i];
# If target + sum is odd or S exceeds sum
if (sum < S or -sum > -S or
(S + sum) % 2 == 1):
# No sultion exists
return 0;
dp = [0]*(((S + sum) // 2) + 1);
dp[0] = 1;
for j in range(len(nums)):
for i in range(len(dp) - 1, nums[j] - 1, -1):
dp[i] += dp[i - nums[j]];
# Return the answer
return dp[len(dp) - 1];
# Driver Code
if __name__ == '__main__':
S = 3;
arr = [1, 2, 3, 4, 5 ];
answer = knapSack(arr, S);
print(answer);
# This code is contributed by Princi Singh
C#
// C# Program to implement
// the above approach
using System;
class GFG{
// Function to call dfs
// to calculate the number of ways
static int knapSack(int[] nums, int S)
{
int sum = 0;
foreach (int i in nums)
sum += i;
// If target + sum is odd or S exceeds sum
if (sum < S || -sum > -S ||
(S + sum) % 2 == 1)
// No sultion exists
return 0;
int[] dp = new int[(S + sum) / 2 + 1];
dp[0] = 1;
foreach (int num in nums)
{
for (int i = dp.Length - 1; i >= num; i--)
{
dp[i] += dp[i - num];
}
}
// Return the answer
return dp[dp.Length - 1];
}
// Driver Code
public static void Main(String[] args)
{
int S = 3;
int[] arr = new int[] { 1, 2, 3, 4, 5 };
int answer = knapSack(arr, S);
Console.WriteLine(answer);
}
}
// This code is contributed by Rajput-Ji
JavaScript
<script>
// Javascript Program to implement
// the above approach
// Function to call dfs
// to calculate the number of ways
function knapSack(nums, S)
{
let sum = 0;
for (let i = 0; i < nums.length; i++)
sum += nums[i];
// If target + sum is odd or S exceeds sum
if (sum < S || -sum > -S || (S + sum) % 2 == 1)
// No sultion exists
return 0;
let dp = new Array(parseInt((S + sum) / 2, 10) + 1);
dp.fill(0);
dp[0] = 1;
for (let num = 0; num < nums.length; num++) {
for (let i = dp.length - 1; i >= nums[num]; i--) {
dp[i] += dp[i - nums[num]];
}
}
// Return the answer
return dp[dp.length - 1];
}
let S = 3;
let arr = [ 1, 2, 3, 4, 5 ];
let answer = knapSack(arr, S);
document.write(answer);
// This code is contributed by divyeshrabadiya07.
</script>
Time Complexity: O(n*(sum + S)), where sum denotes the sum of the array
Auxiliary Space: O(S + sum)
Similar Reads
DSA Tutorial - Learn Data Structures and Algorithms DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
Quick Sort QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
Data Structures Tutorial Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Bubble Sort Algorithm Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Breadth First Search or BFS for a Graph Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Binary Search Algorithm - Iterative and Recursive Implementation Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read
Insertion Sort Algorithm Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Array Data Structure Guide In this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
4 min read
Sorting Algorithms A Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read