Sum of all subsequences of an array
Given an array of n integers. Find the sum of all possible subsequences of an array.
Examples :
Input : arr[] = { 1, 2 }
Output : 6
All possible subsequences are {}, {1}, {2}
and { 1, 2 }
Input : arr[] = { 1, 2, 3 }
Output : 24
We have already discussed two different solutions in below post.
Sum of all Subarrays | Set 1
In this post a different solution is discussed. Let us take a closer look at the problem and try to find a pattern
Let a[] = { 1, 2, 3 }
All subsequences are {}, {1}, {2}, {3}, {1, 2},
{1, 3}, {2, 3}, {1, 2, 3}
So sum of subsequences are 0 + 1 + 2 + 3 + 3 +
4 + 5 + 6 = 24
Here we can observe that in sum every elements
occurs 4 times. Or in general every element
will occur 2^(n-1) times. And we can also
observe that sum of array elements is 6. So
final result will be 6*4.
In general we can find sum of all subsequences by adding all elements of array multiplied by 2(n-1) where n is number of elements in array.
Implementation:
C++
#include <bits/stdc++.h>
using namespace std;
int findSum( int arr[], int n)
{
int sum = 0;
for ( int i = 0; i < n; i++)
sum += arr[i];
return sum * (1 << (n - 1));
}
int main()
{
int arr[] = { 1, 2 };
int n = sizeof (arr) / sizeof (arr[0]);
cout << findSum(arr, n);
return 0;
}
|
Java
public class Main {
static int findSum( int arr[], int n)
{
int sum = 0 ;
for ( int i = 0 ; i < n; i++)
sum += arr[i];
return sum * ( 1 << (n - 1 ));
}
public static void main(String[] args)
{
int arr[] = { 1 , 2 };
int n = arr.length;
System.out.print(findSum(arr, n));
}
}
|
Python
def findSum(arr, n):
sum = 0
for i in range (n):
sum + = arr[i]
return sum * ( 1 << (n - 1 ))
arr = [ 1 , 2 ]
n = len (arr)
print findSum(arr, n)
|
C#
using System;
class GFG
{
static int findSum( int []arr, int n)
{
int sum = 0;
for ( int i = 0; i < n; i++)
sum += arr[i];
return sum * (1 << (n - 1));
}
static public void Main ()
{
int []arr = { 1, 2 };
int n = arr.Length;
Console.WriteLine(findSum(arr, n));
}
}
|
PHP
<?php
function findSum( $arr , $n )
{
$sum = 0;
for ( $i = 0; $i < $n ; $i ++)
$sum += $arr [ $i ];
return $sum * (1 << ( $n - 1));
}
$arr = array ( 1, 2 );
$n = sizeof( $arr );
echo findSum( $arr , $n );
?>
|
Javascript
<script>
function findSum(arr, n)
{
let sum = 0;
for (let i = 0; i < n; i++)
sum += arr[i];
return sum * (1 << (n - 1));
}
let arr = [ 1, 2 ];
let n = arr.length;
document.write(findSum(arr, n));
</script>
|
Last Updated :
18 Sep, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...