Sum of values of all possible non-empty subsets of the given array
Last Updated :
13 Mar, 2022
Given an array arr[] of N integers, the task is to find the sum of values of all possible non-empty subsets of array the given array.
Examples:
Input: arr[] = {2, 3}
Output: 10
All non-empty subsets are {2}, {3} and {2, 3}
Total sum = 2 + 3 + 2 + 3 = 10
Input: arr[] = {2, 1, 5, 6}
Output: 112
Approach: It can be observed that when all the elements are added from all the possible subsets then each element of the original array appears in 2(N – 1) times. Which means contribution of any element arr[i] in the final answer will be arr[i] * 2(N – 1). So, the required answer will be (arr[0] + arr[1] + arr[2] + … + arr[N – 1]) * 2(N – 1).
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int sum( int arr[], int n)
{
int sum = 0;
for ( int i = 0; i < n; i++) {
sum += arr[i];
}
sum = sum * pow (2, n - 1);
return sum;
}
int main()
{
int arr[] = { 2, 1, 5, 6 };
int n = sizeof (arr) / sizeof ( int );
cout << sum(arr, n);
return 0;
}
|
Java
class GFG
{
static int sum( int arr[], int n)
{
int sum = 0 ;
for ( int i = 0 ; i < n; i++)
{
sum += arr[i];
}
sum = sum * ( int )Math.pow( 2 , n - 1 );
return sum;
}
public static void main (String[] args)
{
int arr[] = { 2 , 1 , 5 , 6 };
int n = arr.length;
System.out.println(sum(arr, n));
}
}
|
Python3
def sum ( arr, n):
sum = 0
for i in arr :
sum + = i
sum = sum * pow ( 2 , n - 1 )
return sum
arr = [ 2 , 1 , 5 , 6 ]
n = len (arr)
print ( sum (arr, n))
|
C#
using System;
class GFG
{
static int sum( int [] arr, int n)
{
int sum = 0;
for ( int i = 0; i < n; i++)
{
sum += arr[i];
}
sum = sum * ( int )Math.Pow(2, n - 1);
return sum;
}
public static void Main ()
{
int [] arr = { 2, 1, 5, 6 };
int n = arr.Length;
Console.WriteLine(sum(arr, n));
}
}
|
Javascript
<script>
function sum(arr, n)
{
var sum = 0;
for (i = 0; i < n; i++)
{
sum += arr[i];
}
sum = sum * parseInt(Math.pow(2, n - 1));
return sum;
}
var arr = [ 2, 1, 5, 6 ];
var n = arr.length;
document.write(sum(arr, n));
</script>
|
Time Complexity: O(n)
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...