Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Problems on DP
  • Practice DP
  • MCQs on DP
  • Tutorial on Dynamic Programming
  • Optimal Substructure
  • Overlapping Subproblem
  • Memoization
  • Tabulation
  • Tabulation vs Memoization
  • 0/1 Knapsack
  • Unbounded Knapsack
  • Subset Sum
  • LCS
  • LIS
  • Coin Change
  • Word Break
  • Egg Dropping Puzzle
  • Matrix Chain Multiplication
  • Palindrome Partitioning
  • DP on Arrays
  • DP with Bitmasking
  • Digit DP
  • DP on Trees
  • DP on Graph
Open In App
Next Article:
Maximum subsequence sum with adjacent elements having atleast K difference in index
Next article icon

Count ways to split array into two subsets having difference between their sum equal to K

Last Updated : 29 Apr, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an array A[] of size N and an integer diff, the task is to count the number of ways to split the array into two subsets (non-empty subset is possible) such that the difference between their sums is equal to diff.

Examples:

Input: A[] = {1, 1, 2, 3}, diff = 1  
Output: 3  
Explanation: All possible combinations are as follows: 

  • {1, 1, 2} and {3}
  • {1, 3} and {1, 2}
  • {1, 2} and {1, 3}

All partitions have difference between their sums equal to 1. Therefore, the count of ways is 3.

Input: A[] = {1, 6, 11, 5}, diff=1
Output: 2

 

Naive Approach: The simplest approach to solve the problem is based on the following observations:

Let the sum of elements in the partition subsets S1 and S2 be sum1 and sum2 respectively.
Let sum of the array A[] be X. 
Given, sum1 – sum2 = diff – (1)
Also, sum1 + sum2 = X – (2)

From equations (1) and (2), 
sum1 = (X + diff)/2

Therefore, the task is reduced to finding the number of subsets with a given sum. 
Therefore, the simplest approach is to solve this problem is by generating all the possible subsets and checking whether the subset has the required sum. 

Time Complexity: O(2N)
Auxiliary Space: O(N)

Efficient Approach: To optimize the above approach, the idea is to use Dynamic Programming. Initialize a dp[][] table of size N*X, where dp[i][C] stores the number of subsets of the sub-array A[i…N-1] such that their sum is equal to C. Thus, the recurrence is very trivial as there are only two choices i.e. either consider the ith element in the subset or don’t. So the recurrence relation will be:

dp[i][C] = dp[i – 1][C – A[i]] + dp[i-1][C]

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 the number of ways to divide
// the array into two subsets and such that the
// difference between their sums is equal to diff
int countSubset(int arr[], int n, int diff)
{
    // Store the sum of the set S1
    int sum = 0;
    for (int i = 0; i < n; i++)
        sum += arr[i];
    sum += diff;
    sum = sum / 2;
 
    // Initializing the matrix
    int t[n + 1][sum + 1];
 
    // Number of ways to get sum
    // using 0 elements is 0
    for (int j = 0; j <= sum; j++)
        t[0][j] = 0;
 
    // Number of ways to get sum 0
    // using i elements is 1
    for (int i = 0; i <= n; i++)
        t[i][0] = 1;
 
    // Traverse the 2D array
    for (int i = 1; i <= n; i++) {
        for (int j = 1; j <= sum; j++) {
 
            // If the value is greater
            // than the sum store the
            // value of previous state
            if (arr[i - 1] > j)
                t[i][j] = t[i - 1][j];
 
            else {
                t[i][j] = t[i - 1][j]
                          + t[i - 1][j - arr[i - 1]];
            }
        }
    }
 
    // Return the result
    return t[n][sum];
}
 
// Driver Code
int main()
{
    // Given Input
    int diff = 1, n = 4;
    int arr[] = { 1, 1, 2, 3 };
 
    // Function Call
    cout << countSubset(arr, n, diff);
}
 
 

Java




// Java program for the above approach
import java.io.*;
public class GFG
{
 
    // Function to count the number of ways to divide
    // the array into two subsets and such that the
    // difference between their sums is equal to diff
    static int countSubset(int []arr, int n, int diff)
    {
       
        // Store the sum of the set S1
        int sum = 0;
        for (int i = 0; i < n; i++)
            sum += arr[i];
        sum += diff;
        sum = sum / 2;
     
        // Initializing the matrix
        int t[][] = new int[n + 1][sum + 1];
     
        // Number of ways to get sum
        // using 0 elements is 0
        for (int j = 0; j <= sum; j++)
            t[0][j] = 0;
     
        // Number of ways to get sum 0
        // using i elements is 1
        for (int i = 0; i <= n; i++)
            t[i][0] = 1;
     
        // Traverse the 2D array
        for (int i = 1; i <= n; i++) {
            for (int j = 1; j <= sum; j++) {
     
                // If the value is greater
                // than the sum store the
                // value of previous state
                if (arr[i - 1] > j)
                    t[i][j] = t[i - 1][j];
     
                else {
                    t[i][j] = t[i - 1][j]
                              + t[i - 1][j - arr[i - 1]];
                }
            }
        }
     
        // Return the result
        return t[n][sum];
    }
     
    // Driver Code
    public static void main(String[] args)
    {
         
        // Given Input
        int diff = 1, n = 4;
        int arr[] = { 1, 1, 2, 3 };
     
        // Function Call
        System.out.print(countSubset(arr, n, diff));
    }
}
 
// This code is contributed by AnkThon
 
 

Python3




# Python3 program for the above approach
 
# Function to count the number of ways to divide
# the array into two subsets and such that the
# difference between their sums is equal to diff
def countSubset(arr, n, diff):
     
    # Store the sum of the set S1
    sum = 0
    for i in range(n):
        sum += arr[i]
         
    sum += diff
    sum = sum // 2
 
    # Initializing the matrix
    t = [[0 for i in range(sum + 1)]
            for i in range(n + 1)]
 
    # Number of ways to get sum
    # using 0 elements is 0
    for j in range(sum + 1):
        t[0][j] = 0
 
    # Number of ways to get sum 0
    # using i elements is 1
    for i in range(n + 1):
        t[i][0] = 1
 
    # Traverse the 2D array
    for i in range(1, n + 1):
        for j in range(1, sum + 1):
             
            # If the value is greater
            # than the sum store the
            # value of previous state
            if (arr[i - 1] > j):
                t[i][j] = t[i - 1][j]
            else:
                t[i][j] = t[i - 1][j] + t[i - 1][j - arr[i - 1]]
 
    # Return the result
    return t[n][sum]
 
# Driver Code
if __name__ == '__main__':
     
    # Given Input
    diff, n = 1, 4
    arr = [ 1, 1, 2, 3 ]
 
    # Function Call
    print (countSubset(arr, n, diff))
 
# This code is contributed by mohit kumar 29
 
 

C#




// C# program for the above approach
 
using System;
 
public class GFG
{
 
    // Function to count the number of ways to divide
    // the array into two subsets and such that the
    // difference between their sums is equal to diff
    static int countSubset(int []arr, int n, int diff)
    {
       
        // Store the sum of the set S1
        int sum = 0;
        for (int i = 0; i < n; i++)
            sum += arr[i];
        sum += diff;
        sum = sum / 2;
     
        // Initializing the matrix
        int [,]t = new int[n + 1, sum + 1];
     
        // Number of ways to get sum
        // using 0 elements is 0
        for (int j = 0; j <= sum; j++)
            t[0,j] = 0;
     
        // Number of ways to get sum 0
        // using i elements is 1
        for (int i = 0; i <= n; i++)
            t[i,0] = 1;
     
        // Traverse the 2D array
        for (int i = 1; i <= n; i++) {
            for (int j = 1; j <= sum; j++) {
     
                // If the value is greater
                // than the sum store the
                // value of previous state
                if (arr[i - 1] > j)
                    t[i,j] = t[i - 1,j];
     
                else {
                    t[i,j] = t[i - 1,j]
                              + t[i - 1,j - arr[i - 1]];
                }
            }
        }
     
        // Return the result
        return t[n,sum];
    }
     
    // Driver Code
    public static void Main(string[] args)
    {
         
        // Given Input
        int diff = 1, n = 4;
        int []arr = { 1, 1, 2, 3 };
     
        // Function Call
        Console.Write(countSubset(arr, n, diff));
    }
}
 
// This code is contributed by AnkThon
 
 

Javascript




<script>
 
// JavaScript program for the above approach
 
// Function to count the number of ways to divide
// the array into two subsets and such that the
// difference between their sums is equal to diff
function countSubset(arr, n, diff)
{
    // Store the sum of the set S1
    var sum = 0;
    for (var i = 0; i < n; i++){
        sum += arr[i];
    }
    sum += diff;
    sum = sum / 2;
 
    // Initializing the matrix
    //int t[n + 1][sum + 1];
    var t = new Array(n + 1);
     
    // Loop to create 2D array using 1D array
    for (var i = 0; i < t.length; i++) {
        t[i] = new Array(sum + 1);
    }
     
    // Loop to initialize 2D array elements.
    for (var i = 0; i < t.length; i++) {
        for (var j = 0; j < t[i].length; j++) {
            t[i][j] = 0;
        }
    }
 
    // Number of ways to get sum
    // using 0 elements is 0
    for (var j = 0; j <= sum; j++)
        t[0][j] = 0;
 
    // Number of ways to get sum 0
    // using i elements is 1
    for (var i = 0; i <= n; i++)
        t[i][0] = 1;
 
    // Traverse the 2D array
    for (var i = 1; i <= n; i++) {
        for (var j = 1; j <= sum; j++) {
 
            // If the value is greater
            // than the sum store the
            // value of previous state
            if (arr[i - 1] > j)
                t[i][j] = t[i - 1][j];
 
            else {
                t[i][j] = t[i - 1][j]
                          + t[i - 1][j - arr[i - 1]];
            }
        }
    }
 
    // Return the result
    return t[n][sum];
}
 
// Driver Code
 
// Given Input
var diff = 1;
var n = 4;
var arr = [ 1, 1, 2, 3 ];
 
// Function Call
document.write(countSubset(arr, n, diff));
 
</script>
 
 
Output: 
3

 

Time Complexity: O(S*N), where S = sum of array elements + K/2 
Auxiliary Space: O(S*N)

Efficient approach: space optimization
 

To optimize space complexity we only need to keep track of the values of the previous row in the 2D array to compute the values of the current row. Hence, we can replace the 2D array t[n + 1][sum + 1] with a 1D array dp[sum + 1].

Implementation Steps :

  • Create vector Dp of size sum + 1 and initialize it with 0.
  • Now initialize DP with Base Case dp[0] =1.
  • To calculate answer iterate over subproblems with the help of nested loops and get the current value from previous computation.
  • At last return the answer stored in dp[sum].

Implementation:

C++




// C++ program for above approach
 
#include <bits/stdc++.h>
using namespace std;
 
 
// Function to count the number of ways to divide
// the array into two subsets and such that the
// difference between their sums is equal to diff
int countSubset(int arr[], int n, int diff)
{
    int sum = 0;
    for (int i = 0; i < n; i++)
        sum += arr[i];
    sum += diff;
    sum = sum / 2;
      
      // Initializing the vector Dp
    int dp[sum + 1] = {0};
   
      // Base Case
    dp[0] = 1;
      
      // iterate over subproblems to get the current computation
    for (int i = 0; i < n; i++) {
        for (int j = sum; j >= arr[i]; j--) {
              // update DP from previous values
            dp[j] += dp[j - arr[i]];
        }
    }
      
      // return answer
    return dp[sum];
}
 
// Driver Code
int main()
{
    // Given Input
    int diff = 1, n = 4;
    int arr[] = { 1, 1, 2, 3 };
 
    // Function Call
    cout << countSubset(arr, n, diff);
}
 
// this code is contributed by bhardwajji
 
 

Java




// Java program for above approach
import java.util.*;
 
public class Main
{
   
    // Function to count the number of ways to divide
    // the array into two subsets and such that the
    // difference between their sums is equal to diff
    public static int countSubset(int arr[], int n, int diff)
    {
        int sum = 0;
        for (int i = 0; i < n; i++)
            sum += arr[i];
        sum += diff;
        sum = sum / 2;
 
        // Initializing the vector Dp
        int dp[] = new int[sum + 1];
 
        // Base Case
        dp[0] = 1;
 
        // iterate over subproblems to get the current computation
        for (int i = 0; i < n; i++) {
            for (int j = sum; j >= arr[i]; j--) {
                // update DP from previous values
                dp[j] += dp[j - arr[i]];
            }
        }
 
        // return answer
        return dp[sum];
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        // Given Input
        int diff = 1, n = 4;
        int arr[] = { 1, 1, 2, 3 };
 
        // Function Call
        System.out.println(countSubset(arr, n, diff));
    }
}
 
 

Python3




# Function to count the number of ways to divide
# the array into two subsets and such that the
# difference between their sums is equal to diff
 
 
def countSubset(arr, n, diff):
    # Calculating the sum of all elements
    sum = 0
    for i in range(n):
        sum += arr[i]
    sum += diff
 
    # If sum is odd, then no such subset can exist
    if sum % 2 != 0:
        return 0
 
    # Initializing the vector Dp
    dp = [0] * (sum // 2 + 1)
 
    # Base Case
    dp[0] = 1
 
    # iterate over subproblems to get the current computation
    for i in range(n):
        for j in range(sum // 2, arr[i] - 1, -1):
            # update DP from previous values
            dp[j] += dp[j - arr[i]]
 
    # return answer
    return dp[sum // 2]
 
 
# Given Input
diff = 1
n = 4
arr = [1, 1, 2, 3]
 
# Function Call
print(countSubset(arr, n, diff))
 
 

C#




using System;
 
class MainClass
{
   
  // Function to count the number of ways to divide
  // the array into two subsets and such that the
  // difference between their sums is equal to diff
  static int countSubset(int[] arr, int n, int diff)
  {
    int sum = 0;
    for (int i = 0; i < n; i++) {
      sum += arr[i];
    }
    sum += diff;
    sum = sum / 2;
 
    // Initializing the vector Dp
    int[] dp = new int[sum + 1];
 
    // Base Case
    dp[0] = 1;
 
    // Iterate over subproblems to get the current
    // computation
    for (int i = 0; i < n; i++) {
      for (int j = sum; j >= arr[i]; j--) {
        // Update DP from previous values
        dp[j] += dp[j - arr[i]];
      }
    }
 
    // Return answer
    return dp[sum];
  }
 
  // Driver Code
  public static void Main()
  {
    // Given Input
    int diff = 1, n = 4;
    int[] arr = { 1, 1, 2, 3 };
 
    // Function Call
    Console.WriteLine(countSubset(arr, n, diff));
  }
}
 
 

Javascript




// Function to count the number of ways to divide
// the array into two subsets and such that the
// difference between their sums is equal to diff
function countSubset(arr, n, diff) {
  let sum = 0;
  for (let i = 0; i < n; i++) {
    sum += arr[i];
  }
  sum += diff;
  sum = Math.floor(sum / 2);
 
  // Initializing the vector Dp
  let dp = new Array(sum + 1).fill(0);
 
  // Base Case
  dp[0] = 1;
 
  // Iterate over subproblems to get the current
  // computation
  for (let i = 0; i < n; i++) {
    for (let j = sum; j >= arr[i]; j--) {
      // Update DP from previous values
      dp[j] += dp[j - arr[i]];
    }
  }
 
  // Return answer
  return dp[sum];
}
 
// Driver Code
let diff = 1,
  n = 4;
let arr = [1, 1, 2, 3];
 
// Function Call
console.log(countSubset(arr, n, diff));
 
 
Output
3

Time Complexity: O(S*N), where S = sum of array elements + K/2 
Auxiliary Space: O(S)



Next Article
Maximum subsequence sum with adjacent elements having atleast K difference in index

S

sonigurleen60
Improve
Article Tags :
  • Arrays
  • C++ Programs
  • Data Structures
  • DSA
  • Dynamic Programming
  • Mathematical
  • partition
  • subset
Practice Tags :
  • Arrays
  • Data Structures
  • Dynamic Programming
  • Mathematical
  • subset

Similar Reads

  • Count the pairs in an array such that the difference between them and their indices is equal
    Given an array arr[] of size N, the task is to count the number of pairs (arr[i], arr[j]) such that arr[j] - arr[i] = j - i.Examples: Input: arr[] = {5, 2, 7} Output: 1 The only valid pair is (arr[0], arr[2]) as 7 - 5 = 2 - 0 = 2.Input: arr[] = {1, 2, 3, 4} Output: 6 Approach: A pair (arr[i], arr[j]
    5 min read
  • Split squares of first N natural numbers into two sets with minimum absolute difference of their sums
    Given an integer N, the task is to partition the squares of first N( always a multiple of 8 ) natural numbers into two sets such that the difference of their subset sums is minimized. Print both the subsets as the required answer. Examples: Input: N = 8Output:01 16 36 494 9 25 64Explanation: Squares
    9 min read
  • Count ways to place '+' and '-' in front of array elements to obtain sum K
    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 = 1Output: 3Explanation
    10 min read
  • Maximum subsequence sum with adjacent elements having atleast K difference in index
    Given an array arr[] consisting of integers of length N and an integer K (1 ? k ? N), the task is to find the maximum subsequence sum in the array such that adjacent elements in that subsequence have at least a difference of K in their indices in the original array. Examples: Input: arr[] = {1, 2, -
    8 min read
  • Count of subsets having sum of min and max element less than K
    Given an integer array arr[] and an integer K, the task is to find the number of non-empty subsets S such that min(S) + max(S) < K.Examples: Input: arr[] = {2, 4, 5, 7} K = 8 Output: 4 Explanation: The possible subsets are {2}, {2, 4}, {2, 4, 5} and {2, 5}Input:: arr[] = {2, 4, 2, 5, 7} K = 10 Ou
    5 min read
  • Count of Arrays of size N with elements in range [0, (2^K)-1] having maximum sum & bitwise AND 0
    Given two integers N and K, The task is to find the count of all possible arrays of size N with maximum sum & bitwise AND of all elements as 0. Also, elements should be within the range of 0 to 2K-1. Examples: Input: N = 3, K = 2Output: 9Explanation: 22 - 1 = 3, so elements of arrays should be b
    6 min read
  • Count maximum number of disjoint pairs having one element not less than K times the other
    Given an array arr[] and a positive integer K, the task is to find the maximum count of disjoint pairs (arr[i], arr[j]) such that arr[j] ? K * arr[i]. Examples: Input: arr[] = { 1, 9, 4, 7, 3 }, K = 2Output: 2Explanation:There can be 2 possible pairs that can formed from the given array i.e., (4, 1)
    6 min read
  • Count of subarrays of size K which is a permutation of numbers from 1 to K
    Given an array arr of distinct integers, the task is to find the count of sub-arrays of size i having all elements from 1 to i, in other words, the sub-array is any permutation of elements from 1 to i, with 1 < = i <= N. Examples: Input: arr[] = {2, 3, 1, 5, 4} Output: 3 Explanation: we have {
    6 min read
  • Subsets with sum divisible by m
    Given an array of size n and an integer m, the task is to find the number of non-empty subsequences such that the sum of the subsequence is divisible by m. Note: The sum of all array elements in small, i.e., it is within integer range.m > 0.Examples: Input : arr[] = [1, 2, 3, 4], m = 2Output : 7
    15+ min read
  • Count ways to split array into pair of subsets with difference between their sum equal to K
    Given an array arr[] consisting of N integers and an integer K, the task is to find the number of ways to split the array into a pair of subsets such that the difference between their sum is K. Examples: Input: arr[] = {1, 1, 2, 3}, K = 1Output: 3Explanation:Following splits into a pair of subsets s
    15 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences