Count ways to place '+' and '-' in front of array elements to obtain sum K
Last Updated :
10 Apr, 2023
Given an array A[] consisting of N non-negative integers, and an integer K, the task is to find the number of ways '+' and '-' operators can be placed in front of elements of the array A[] such that the sum of the array becomes K.
Examples:
Input: A[] = {1, 1, 2, 3}, N = 4, K = 1
Output: 3
Explanation: Three possible ways are:
- + 1 + 1 + 2 - 3 = 1
- + 1 - 1 - 2 + 3 = 1
- - 1 + 1 - 1 + 3 = 1
Input: A[] = {1, 1, 1, 1, 1}, N = 5, K = 3
Output: 6
Approach: The problem can be solved based on the following observations:
- Store the sum of elements having '+' in front of that element and '-' in front of that element in variables, say P1 and P2, such that the sum of the array becomes K.
- Store the total sum of the array A[] in a variable, say K.
- Therefore, following equations arises:
- P1 + P2 = sum
- P1 - P2 = K
- Solving the above equations obtains P1 = (sum + K) / 2.
- Therefore, the problem has transformed into finding the number of subsets with sum P1.
- If an element of A is equal to 0, both '+' and '-' operators work in valid arrangements, thus, the 0s can be safely ignored and separately calculated.
Hence, the problem can be solved using Dynamic Programming. Follow the steps below to solve the problem:
- Calculate and store the sum of elements of the array A[] and the number of 0s in A[] in variables sum and c respectively.
- If K is greater than sum or (sum + K) is odd, return 0.
- Add K to sum and divide it by 2, i.e. sum = (sum + K) / 2, which is the required sum. Find the number of subsets equal to that sum.
- Create a 2D dp array of dimensions N*sum. where dp[i][j] represents the number of subsets up to i-1 that have sum j.
- The base cases required to be considered are as follows:
- dp[0][i] = 0, for 0 <= i <= sum, as no elements from the array A[] has been considered
- dp[i][0] = 1, for 0 <= i <= N, as obtaining a sum 0 is always possible.
- Iterate from 1 to N, and for each current index i, perform the following operations:
- Iterate from 1 to sum and for each current index j, perform the following transitions:
- If A[i - 1] is less than j and A[i - 1] is not equal to 0, set dp[i][j] = dp[i - 1][j] + dp[i - 1][j - A[i - 1]].
- Otherwise, copy the previous state, i.e. dp[i][j] = dp[i - 1][j].
- Finally, return the product of dp[N][sum] and 2c (to account for the 0s) i.e dp[N][sum]*2c.
Below is the implementation of the above approach:
C++
// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
// Function to count number of ways
// '+' and '-' operators can be placed
// in front of array elements to make
// the sum of array elements equal to K
int solve(int A[], int N, int K)
{
// Stores sum of the array
int sum = 0;
// Stores count of 0s in A[]
int c = 0;
// Traverse the array
for (int i = 0; i < N; i++) {
// Update sum
sum += A[i];
// Update count of 0s
if (A[i] == 0)
c++;
}
// Conditions where no arrangements
// are possible which adds up to K
if (K > sum || (sum + K) % 2)
return 0;
// Required sum
sum = (sum + K) / 2;
// Dp array
int dp[N + 1][sum + 1];
// Base cases
for (int i = 0; i <= sum; i++)
dp[0][i] = 0;
for (int i = 0; i <= N; i++)
dp[i][0] = 1;
// Fill the dp array
for (int i = 1; i <= N; i++) {
for (int j = 1; j <= sum; j++) {
if (A[i - 1] <= j && A[i - 1])
dp[i][j] = dp[i - 1][j]
+ dp[i - 1][j - A[i - 1]];
else
dp[i][j] = dp[i - 1][j];
}
}
// Return answer
return dp[N][sum] + pow(2, c);
}
// Driver Code
int main()
{
// Input
int A[] = { 1, 1, 2, 3 };
int N = sizeof(A) / sizeof(A[0]);
int K = 3;
// Function call
cout << solve(A, N, K) << endl;
return 0;
}
Java
// Java program for the above approach
import java.util.*;
class GFG{
// Function to count number of ways
// '+' and '-' operators can be placed
// in front of array elements to make
// the sum of array elements equal to K
static int solve(int A[], int N, int K)
{
// Stores sum of the array
int sum = 0;
// Stores count of 0s in A[]
int c = 0;
// Traverse the array
for (int i = 0; i < N; i++) {
// Update sum
sum += A[i];
// Update count of 0s
if (A[i] == 0)
c++;
}
// Conditions where no arrangements
// are possible which adds up to K
if ((K > sum) || (((sum + K) % 2) != 0))
return 0;
// Required sum
sum = (sum + K) / 2;
// Dp array
int dp[][] = new int[N + 1][sum + 1];
// Base cases
for (int i = 0; i <= sum; i++)
dp[0][i] = 0;
for (int i = 0; i <= N; i++)
dp[i][0] = 1;
// Fill the dp array
for (int i = 1; i <= N; i++) {
for (int j = 1; j <= sum; j++) {
if ((A[i - 1] <= j) && (A[i - 1] != 0))
dp[i][j] = dp[i - 1][j]
+ dp[i - 1][j - A[i - 1]];
else
dp[i][j] = dp[i - 1][j];
}
}
// Return answer
return dp[N][sum] + (int)Math.pow(2, c);
}
// Driver Code
public static void main(String[] args)
{
// Input
int A[] = { 1, 1, 2, 3 };
int N = A.length;
int K = 3;
// Function call
System.out.print(solve(A, N, K));
}
}
// This code is contributed by sanjoy_62.
Python3
# Python3 program for the above approach
# Function to count number of ways
# '+' and '-' operators can be placed
# in front of array elements to make
# the sum of array elements equal to K
def solve(A, N, K):
# Stores sum of the array
sum = 0
# Stores count of 0s in A[]
c = 0
# Traverse the array
for i in range(N):
# Update sum
sum += A[i]
# Update count of 0s
if (A[i] == 0):
c += 1
# Conditions where no arrangements
# are possible which adds up to K
if (K > sum or (sum + K) % 2):
return 0
# Required sum
sum = (sum + K) // 2
# Dp array
dp = [[0 for i in range(sum + 1)]
for j in range(N + 1)]
# Base cases
for i in range(sum + 1):
dp[0][i] = 0
for i in range(N + 1):
dp[i][0] = 1
# Fill the dp array
for i in range(1, N + 1, 1):
for j in range(1, sum + 1, 1):
if (A[i - 1] <= j and A[i - 1]):
dp[i][j] = (dp[i - 1][j] +
dp[i - 1][j - A[i - 1]])
else:
dp[i][j] = dp[i - 1][j]
# Return answer
return dp[N][sum] + pow(2, c)
# Driver Code
if __name__ == '__main__':
# Input
A = [ 1, 1, 2, 3 ]
N = len(A)
K = 3
# Function call
print(solve(A, N, K))
# This code is contributed by SURENDRA_GANGWAR
C#
// C# program for the above approach
using System;
public class GFG
{
// Function to count number of ways
// '+' and '-' operators can be placed
// in front of array elements to make
// the sum of array elements equal to K
static int solve(int[] A, int N, int K)
{
// Stores sum of the array
int sum = 0;
// Stores count of 0s in A[]
int c = 0;
// Traverse the array
for (int i = 0; i < N; i++) {
// Update sum
sum += A[i];
// Update count of 0s
if (A[i] == 0)
c++;
}
// Conditions where no arrangements
// are possible which adds up to K
if ((K > sum) || (((sum + K) % 2) != 0))
return 0;
// Required sum
sum = (sum + K) / 2;
// Dp array
int[, ] dp= new int[N + 1, sum + 1];
// Base cases
for (int i = 0; i <= sum; i++)
dp[0, i] = 0;
for (int i = 0; i <= N; i++)
dp[i,0] = 1;
// Fill the dp array
for (int i = 1; i <= N; i++) {
for (int j = 1; j <= sum; j++) {
if ((A[i - 1] <= j) && (A[i - 1] != 0))
dp[i,j] = dp[i - 1,j]
+ dp[i - 1,j - A[i - 1]];
else
dp[i,j] = dp[i - 1,j];
}
}
// Return answer
return dp[N, sum] + (int)Math.Pow(2, c);
}
// Driver code
static public void Main ()
{
// Input
int[] A = { 1, 1, 2, 3 };
int N = A.Length;
int K = 3;
// Function call
Console.Write(solve(A, N, K));
}
}
// This code is contributed by offbeat
JavaScript
<script>
// JavaScript program for the above approach
// Function to count number of ways
// '+' and '-' operators can be placed
// in front of array elements to make
// the sum of array elements equal to K
function solve(A, N, K)
{
// Stores sum of the array
let sum = 0;
// Stores count of 0s in A[]
let c = 0;
// Traverse the array
for (let i = 0; i < N; i++) {
// Update sum
sum += A[i];
// Update count of 0s
if (A[i] == 0)
c++;
}
// Conditions where no arrangements
// are possible which adds up to K
if (K > sum || (sum + K) % 2)
return 0;
// Required sum
sum = (sum + K) / 2;
// Dp array
let dp = new Array(N + 1);
for (var i = 0; i < dp.length; i++) {
dp[i] = new Array(sum + 1);
}
// Base cases
for (let i = 0; i <= sum; i++)
dp[0][i] = 0;
for (let i = 0; i <= N; i++)
dp[i][0] = 1;
// Fill the dp array
for (let i = 1; i <= N; i++) {
for (let j = 1; j <= sum; j++) {
if (A[i - 1] <= j && A[i - 1])
dp[i][j] = dp[i - 1][j]
+ dp[i - 1][j - A[i - 1]];
else
dp[i][j] = dp[i - 1][j];
}
}
// Return answer
return dp[N][sum] + Math.pow(2, c);
}
// Driver Code
// Input
let A = [1, 1, 2, 3];
let N = A.length;
let K = 3;
// Function call
document.write(solve(A, N, K));
// This code is contributed by Potta Lokesh
</script>
Time Complexity: O(N * sum) where N is the size of the array A and sum is the target sum. This is because we are filling a 2D DP array of size (N+1) x (sum+1) with nested loops.
Auxiliary Space: O(N * sum)
Similar Reads
Count number of pairs with positive sum in an array Given an array arr[] of N integers, the task is to count the number of pairs with positive sum. Examples: Input: arr[] = {-7, -1, 3, 2} Output: 3 Explanation: The pairs with positive sum are: {-1, 3}, {-1, 2}, {3, 2}. Input: arr[] = {-4, -2, 5} Output: 2 Explanation: The pairs with positive sum are:
8 min read
Number of positions such that adding K to the element is greater than sum of all other elements Given an array arr[] and a number K. The task is to find out the number of valid positions i such that (arr[i] + K) is greater than sum of all elements of array excluding arr[i].Examples: Input: arr[] = {2, 1, 6, 7} K = 4 Output: 1 Explanation: There is only 1 valid position i.e 4th. After adding 4
5 min read
C++ Program to Count pairs with given sum Given an array of integers, and a number 'sum', find the number of pairs of integers in the array whose sum is equal to 'sum'. Examples: Input : arr[] = {1, 5, 7, -1}, sum = 6 Output : 2 Pairs with sum 6 are (1, 5) and (7, -1) Input : arr[] = {1, 5, 7, -1, 5}, sum = 6 Output : 3 Pairs with sum 6 are
4 min read
Find all possible values of K such that the sum of first N numbers starting from K is G Given a positive integer G, the task is to find the number of values of K such that the sum of the first N numbers starting from K is G i.e., (K + (K + 1) + ... + (K + N - 1)) = G, where N can be any positive integer. Examples: Input: G = 10Output: 2Explanation:Following are the possible values of K
9 min read
Count of Ways to obtain given Sum from the given Array elements 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 Ou
15+ min read