The Wayback Machine - https://web.archive.org/web/20240624070155/https://www.geeksforgeeks.org/sum-subsets-dynamic-programming/
Open In App

Sum over Subsets | Dynamic Programming

Last Updated : 29 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Prerequisite: Basic Dynamic Programming, Bitmasks 
Consider the following problem where we will use Sum over subset Dynamic Programming to solve it. 
Given an array of 2n integers, we need to calculate function F(x) = ?Ai such that x&i==i for all x. i.e, i is a bitwise subset of x. i will be a bitwise subset of mask x, if x&i==i.
Examples: 
 

Input: A[] = {7, 12, 14, 16} , n = 2 Output: 7, 19, 21, 49 Explanation: There will be 4 values of x: 0,1,2,3 So, we need to calculate F(0),F(1),F(2),F(3). Now, F(0) = A0 = 7 F(1) = A0 + A1 = 19 F(2) = A0 + A2 = 21 F(3) = A0 + A1 + A2 + A3 = 49 Input: A[] = {7, 11, 13, 16} , n = 2 Output: 7, 18, 20, 47 Explanation: There will be 4 values of x: 0,1,2,3 So, we need to calculate F(0),F(1),F(2),F(3). Now, F(0) = A0 = 7 F(1) = A0 + A1 = 18 F(2) = A0 + A2 = 20 F(3) = A0 + A1 + A2 + A3 = 47


 


Brute-Force Approach: 
Iterate for all the x from 0 to (2n-1) . Calculate the bitwise subsets of all the x and sum it up for every x.
Time-Complexity: O(4^n)
Below is the implementation of above idea:
 

C++

// CPP program for brute force
// approach of SumOverSubsets DP
#include <bits/stdc++.h>
using namespace std;
  
// function to print the sum over subsets value
void SumOverSubsets(int a[], int n) {
  
  // array to store the SumOverSubsets
  int sos[1 << n] = {0};
  
  // iterate for all possible x
  for (int x = 0; x < (1 << n); x++) {
  
    // iterate for all possible bitwise subsets
    for (int i = 0; i < (1 << n); i++) {
  
      // if i is a bitwise subset of x
      if ((x & i) == i)
        sos[x] += a[i];
    }
  }
  
  // printa all the subsets
  for (int i = 0; i < (1 << n); i++)
    cout << sos[i] << " ";
}
  
// Driver Code
int main() {
  int a[] = {7, 12, 14, 16};
  int n = 2;
  SumOverSubsets(a, n);
  return 0;
}

Java

// Java program for brute force
// approach of SumOverSubsets DP
  
class GFG{
  
// function to print the
// sum over subsets value
static void SumOverSubsets(int a[], int n) {
  
// array to store the SumOverSubsets
int sos[] = new int [1 << n];
  
  
// iterate for all possible x
for (int x = 0; x < (1 << n); x++) {
  
    // iterate for all possible
        // bitwise subsets
    for (int i = 0; i < (1 << n); i++) {
  
    // if i is a bitwise subset of x
    if ((x & i) == i)
        sos[x] += a[i];
    }
}
  
// printa all the subsets
for (int i = 0; i < (1 << n); i++)
    System.out.printf("%d ", sos[i]);
}
  
// Driver Code
public static void main(String[] args) {
int a[] = {7, 12, 14, 16};
int n = 2;
SumOverSubsets(a, n);
}
}
  
// This code is contributed by 
// Smitha Dinesh Semwal

Python3

# Python 3 program
# for brute force
# approach of SumOverSubsets DP
  
# function to print the
# sum over subsets value
def SumOverSubsets(a, n):
  
    # array to store
    # the SumOverSubsets
    sos = [0] * (1 << n)
      
    # iterate for all possible x
    for x in range(0,(1 << n)): 
      
        # iterate for all
        # possible bitwise subsets
        for i in range(0,(1 << n)):  
      
            # if i is a bitwise subset of x
            if ((x & i) == i):
                sos[x] += a[i]
              
      
      
    # printa all the subsets
    for i in range(0,(1 << n)): 
        print(sos[i],end = " ")
  
  
# Driver Code
a = [7, 12, 14, 16]
n = 2
SumOverSubsets(a, n)
  
# This code is contributed by
# Smitha Dinesh Semwal

C#

// C# program for brute force
// approach of SumOverSubsets DP
using System;
  
class GFG {
      
    // function to print the
    // sum over subsets value
    static void SumOverSubsets(int []a, int n)
    {
      
        // array to store the SumOverSubsets
        int []sos = new int [1 << n];
          
          
        // iterate for all possible x
        for (int x = 0; x < (1 << n); x++) 
        {
          
            // iterate for all possible
            // bitwise subsets
            for (int i = 0; i < (1 << n); i++) 
            {
          
                // if i is a bitwise subset of x
                if ((x & i) == i)
                    sos[x] += a[i];
            }
        }
          
        // printa all the subsets
        for (int i = 0; i < (1 << n); i++)
            Console.Write(sos[i] + " ");
    }
      
    // Driver function
    public static void Main()
    {
        int []a = {7, 12, 14, 16};
        int n = 2;
        SumOverSubsets(a, n);
    }
}
  
// This code is contributed by Sam007

PHP

<?php
// PHP program for brute force
// approach of SumOverSubsets DP
  
// function to print the sum 
// over subsets value
function SumOverSubsets($a, $n)
{
  
    // array to store the SumOverSubsets
    $sos = array(1 << $n);
      
    for($i = 0 ;$i < (1 << $n); $i++)
        $sos[$i] = 0; 
      
    // iterate for all possible x
    for ($x = 0; $x < (1 << $n); $x++)
    {
      
        // iterate for all possible 
        // bitwise subsets
        for($i = 0; $i < (1 << $n); $i++)
        {
      
            // if i is a bitwise
            // subset of x
            if (($x & $i) == $i)
                $sos[$x] += $a[$i];
        }
    }
      
    // printa all the subsets
    for ($i = 0; $i < (1 << $n); $i++)
        echo $sos[$i] . " ";
}
  
// Driver Code
$a = array(7, 12, 14, 16);
$n = 2;
SumOverSubsets($a, $n);
  
// This code is contributed by Sam007
?>

Javascript

<script>
    // Javascript program for brute force
    // approach of SumOverSubsets DP
      
    // function to print the
    // sum over subsets value
    function SumOverSubsets(a, n)
    {
       
        // array to store the SumOverSubsets
        let sos = new Array(1 << n);
        sos.fill(0);
           
           
        // iterate for all possible x
        for (let x = 0; x < (1 << n); x++)
        {
           
            // iterate for all possible
            // bitwise subsets
            for (let i = 0; i < (1 << n); i++)
            {
           
                // if i is a bitwise subset of x
                if ((x & i) == i)
                    sos[x] += a[i];
            }
        }
           
        // printa all the subsets
        for (let i = 0; i < (1 << n); i++)
            document.write(sos[i] + " ");
    }
      
    let a = [7, 12, 14, 16];
    let n = 2;
    SumOverSubsets(a, n);
          
</script>

Output: 
 

7 19 21 49

. 
Sub-Optimal Approach: 
The brute-force algorithm can be easily improved by just iterating over bitwise subsets. Instead of iterating for every i, we can simply iterate for the bitwise subsets only. Iterating backward for i=(i-1)&x gives us every bitwise subset, where i starts from x and ends at 1. If the mask x has k set bits, we do 2k iterations. A number of k set bits will have 2k bitwise subsets. Therefore total number of mask x with k set bits is[Tex]{n \choose k}          [/Tex]. Therefore the total number of iterations is ?[Tex]{n \choose k}          [/Tex]2k = 3n 
Time Complexity: O(3n)
Below is the implementation of above idea: 
 

C++

// CPP program for sub-optimal
// approach of SumOverSubsets DP
#include <bits/stdc++.h>
using namespace std;
  
// function to print the sum over subsets value
void SumOverSubsets(int a[], int n) {
  
  // array to store the SumOverSubsets
  int sos[1 << n] = {0};
  
  // iterate for all possible x
  for (int x = 0; x < (1 << n); x++) {
    sos[x] = a[0];
  
    // iterate for the bitwise subsets only
    for (int i = x; i > 0; i = (i - 1) & x)
      sos[x] += a[i];
  }
  
  // print all the subsets
  for (int i = 0; i < (1 << n); i++)
    cout << sos[i] << " ";
}
  
// Driver Code
int main() {
  int a[] = {7, 12, 14, 16};
  int n = 2;
  SumOverSubsets(a, n);
  return 0;
}

Java

// java program for sub-optimal
// approach of SumOverSubsets DP
public class GFG {
      
    // function to print the sum over
    // subsets value
    static void SumOverSubsets(int a[], int n)
    {
      
        // array to store the SumOverSubsets
        int sos[] = new int[(1 << n)];
          
        // iterate for all possible x
        for (int x = 0; x < (1 << n); x++) {
            sos[x] = a[0];
          
            // iterate for the bitwise subsets only
            for (int i = x; i > 0; i = (i - 1) & x)
                sos[x] += a[i];
        }
          
        // print all the subsets
        for (int i = 0; i < (1 << n); i++)
            System.out.print(sos[i] + " ");
    }
      
    // Driver code
    public static void main(String args[])
    {
        int a[] = {7, 12, 14, 16};
        int n = 2;
          
        SumOverSubsets(a, n);
    }
}
  
// This code is contributed by Sam007

Python3

# Python program for sub-optimal
# approach of SumOverSubsets DP
  
# function to print sum over subsets value
def SumOverSubsets(a, n):
    sos = [0]*(1 << n)
  
    # iterate for all possible x
    for x in range((1 << n)):
        sos[x] = a[0]
          
        # iterate for the bitwise subsets only
        i = x
  
        while i > 0:
          sos[x] += a[i]
          i = ((i - 1) & x)
  
  # print all the subsets
    for i in range(1<<n):
        print(sos[i], end = " ")
  
# Driver Code
if __name__ == '__main__':
    a = [7, 12, 14, 16]
    n = 2
    SumOverSubsets(a, n)
  
# This code is contributed by mohit kumar 29.

C#

// C# program for sub-optimal
// approach of SumOverSubsets DP
using System;
  
class GFG {
      
    // function to print the sum over
    // subsets value
    static void SumOverSubsets(int []a, int n)
    {
      
        // array to store the SumOverSubsets
        int []sos = new int[(1 << n)];
          
        // iterate for all possible x
        for (int x = 0; x < (1 << n); x++) {
            sos[x] = a[0];
          
            // iterate for the bitwise subsets only
            for (int i = x; i > 0; i = (i - 1) & x)
                sos[x] += a[i];
        }
          
        // print all the subsets
        for (int i = 0; i < (1 << n); i++)
        Console.Write(sos[i] + " ");
    }
      
    // Driver code
    static void Main()
    {
        int []a = {7, 12, 14, 16};
        int n = 2;
          
        SumOverSubsets(a, n);
    }
}
  
// This code is contributed by Sam007.

PHP

<?php
// PHP program for sub-optimal
// approach of SumOverSubsets DP
  
// function to print the 
// sum over subsets value
function SumOverSubsets($a,$n) 
{
  
    // array to store the SumOverSubsets
    $sos=array(1 << $n);
      
    // iterate for all possible x
    for ($x = 0; $x < (1 << $n); $x++) 
    {
        $sos[$x] = $a[0];
      
        // iterate for the bitwise
        // subsets only
        for ($i = $x; $i > 0; $i = ($i - 1) & $x)
        $sos[$x] += $a[$i];
    }
      
    // print all the subsets
    for ($i = 0; $i < (1 << $n); $i++)
        echo $sos[$i] . " ";
}
  
// Driver Code
$a = array(7, 12, 14, 16);
$n = 2;
SumOverSubsets($a, $n);
  
// This code is contributed by Sam007.
?>

Javascript

<script>    
    // Javascript program for sub-optimal
    // approach of SumOverSubsets DP
      
    // function to print the sum over
    // subsets value
    function SumOverSubsets(a, n)
    {
       
        // array to store the SumOverSubsets
        let sos = new Array((1 << n));
        sos.fill(0);
           
        // iterate for all possible x
        for (let x = 0; x < (1 << n); x++) {
            sos[x] = a[0];
           
            // iterate for the bitwise subsets only
            for (let i = x; i > 0; i = (i - 1) & x)
                sos[x] += a[i];
        }
           
        // print all the subsets
        for (let i = 0; i < (1 << n); i++)
            document.write(sos[i] + " ");
    }
      
    let a = [7, 12, 14, 16];
    let n = 2;
  
    SumOverSubsets(a, n);
  
</script>


Output: 
 

7 19 21 49

Time Complexity: O(n*2n) 

Auxiliary Space: O(2n)

Reference: 



Previous Article
Next Article

Similar Reads

Count of index subsets such that maximum of values over these indices in A is at least total sum over B
Given two arrays A[] and B[] consisting of N positive integers, the task is to find the total number of subsets of indices such that the maximum value in the array A[] over all these indices is greater than or equal to the sum of all values over these indices in the array B[]. Examples: Input: A[] = {3, 1}, B[] = {1, 2}Output: 2Explanation:The tota
11 min read
Divide array in two Subsets such that sum of square of sum of both subsets is maximum
Given an integer array arr[], the task is to divide this array into two non-empty subsets such that the sum of the square of the sum of both the subsets is maximum and sizes of both the subsets must not differ by more than 1.Examples: Input: arr[] = {1, 2, 3} Output: 26 Explanation: Sum of Subset Pairs are as follows (1)2 + (2 + 3)2 = 26 (2)2 + (1
6 min read
Sum of subsets of all the subsets of an array | O(3^N)
Given an array arr[] of length N, the task is to find the overall sum of subsets of all the subsets of the array.Examples: Input: arr[] = {1, 1} Output: 6 All possible subsets: a) {} : 0 All the possible subsets of this subset will be {}, Sum = 0 b) {1} : 1 All the possible subsets of this subset will be {} and {1}, Sum = 0 + 1 = 1 c) {1} : 1 All t
6 min read
Sum of subsets of all the subsets of an array | O(2^N)
Given an array arr[] of length N, the task is to find the overall sum of subsets of all the subsets of the array.Examples: Input: arr[] = {1, 1} Output: 6 All possible subsets: a) {} : 0 All the possible subsets of this subset will be {}, Sum = 0 b) {1} : 1 All the possible subsets of this subset will be {} and {1}, Sum = 0 + 1 = 1 c) {1} : 1 All t
6 min read
Sum of subsets of all the subsets of an array | O(N)
Given an array arr[] of length N, the task is to find the overall sum of subsets of all the subsets of the array.Examples: Input: arr[] = {1, 1} Output: 6 All possible subsets: a) {} : 0 All the possible subsets of this subset will be {}, Sum = 0 b) {1} : 1 All the possible subsets of this subset will be {} and {1}, Sum = 0 + 1 = 1 c) {1} : 1 All t
7 min read
Find sum of difference of maximum and minimum over all possible subsets of size K
Given an array arr[] of N integers and an integer K, the task is to find the sum of the difference between the maximum and minimum elements over all possible subsets of size K. Examples: Input: arr[] = {1, 1, 3, 4}, K = 2Output: 11Explanation:There are 6 subsets of the given array of size K(= 2). They are {1, 1}, {1, 3}, {1, 4}, {1, 3}, {1, 4} and
12 min read
Partition an array of non-negative integers into two subsets such that average of both the subsets is equal
Given an array of size N. The task is to partition the given array into two subsets such that the average of all the elements in both subsets is equal. If no such partition exists print -1. Otherwise, print the partitions. If multiple solutions exist, print the solution where the length of the first subset is minimum. If there is still a tie then p
14 min read
Split array into minimum number of subsets such that elements of all pairs are present in different subsets at least once
Given an array arr[] consisting of N distinct integers, the task is to find the minimum number of times the array needs to be split into two subsets such that elements of each pair are present into two different subsets at least once. Examples: Input: arr[] = { 3, 4, 2, 1, 5 } Output: 3 Explanation: Possible pairs are { (1, 2), (1, 3), (1, 4), (1,
6 min read
Maximum number of subsets an array can be split into such that product of their minimums with size of subsets is at least K
Given an array arr[] consisting of N integers and an integer K, the task is to find the maximum number of disjoint subsets that the given array can be split into such that the product of the minimum element of each subset with the size of the subset is at least K. Examples: Input: arr[] = {7, 11, 2, 9, 5}, K = 10Output: 2Explanation:All such disjoi
8 min read
Dynamic Programming in Game Theory for Competitive Programming
In the fast-paced world of competitive programming, mastering dynamic programming in game theory is the key to solving complex strategic challenges. This article explores how dynamic programming in game theory can enhance your problem-solving skills and strategic insights, giving you a competitive edge. Whether you're a seasoned coder or a newcomer
15+ min read
three90RightbarBannerImg