# Sum of subset differences in C++

C++Server Side ProgrammingProgramming

In this problem, we are given a set S of n number. Our task is to create a program to find the sum of subset difference which is the difference of last and first elements of subset.

The formula is,

sumSubsetDifference = Σ [last(s) - first(s)]
s are subsets of the set S.

Let’s take an example to understand the problem,

Input

S = {1, 2, 9} n = 3

Output

Explanation − All subset are −

{1}, last(s) - first(s) = 0
{2}, last(s) - first(s) = 0
{9}, last(s) - first(s) = 0
{1, 2}, last(s) - first(s) = 1
{1, 9}, last(s) - first(s) = 8
{2, 9}, last(s) - first(s) = 7
{1, 2, 9}, last(s) - first(s) = 8
Sum = 1 + 8 + 7 + 8 = 24

A simple solution to the problem is to find the difference between last and first for all subsets and then add them to get the sum output. This is not most effective solution, so lets discuss a more efficient solution.

For a set S of n elements, the sum can also be computed using the number of all subsets starting from an element of the array. And the summing it for find the result.

So,

sumSetDifference(S) = Σ [last(s) - Σfirst(s)]

So, for a set S with elements {s1, s2, s3, … sn}.

Subset starting with s1 can be made using the combination of elements with {s2, s3, … sn}. This will gives 2n-1 sets.

Similarly for subset starting with s2 gives 2n-2 sets.

Generalizing it, subset starting with Si given 2n-i.

So, the sum of first element of all subsets is −

SumFirst = a1.2n-1 + a2.2n-2 + a3.2n-3 + … + an.2n-n

Similarly, we will calculate the sumLast fixing the last element.

SumLast = a1.2n-n + a1.2n - (n-1) + a3.2n - (n-2) + ... + an.2n - (n-(n-1))

## Example

Program to illustrate the above solution,

Live Demo

#include<iostream>
#include<math.h>
using namespace std;
int CalcSumFirst(int S[], int n) {
int sum = 0;
for (int i = 0; i < n; i++)
sum = sum + (S[i] * pow(2, n-i-1));
return sum;
}
int CalcSumLast(int S[], int n) {
int sum = 0;
for (int i = 0; i < n; i++)
sum = sum + (S[i] * pow(2, i));
return sum;
}
int main() {
int S[] = {1, 4, 9, 6};
int n = 4;
int sumSetDiff = CalcSumLast(S, n) - CalcSumFirst(S, n);
printf("The sum of subset differences is %d", sumSetDiff);
return 0;
}

## Output

The sum of subset differences is 45