Find Sum of all unique subarray sum for a given array in C++

In this problem, we are given an array arr[] consisting of n integer values. Our task is to find the sum of all unique subarray sum for a given array. Subarray sum is the sum of elements of the given subarray.

Let's take an example to understand the problem,

Input : arr[] = {1, 2, 4}
Output : 23

Explanation

All subarrays of the given array are :
(1), (2), (4), (1, 2), (2, 4), (1, 2, 4)
Sum of subarrays = 1 + 2 + 4 + (1+2) + (2+4) + (1+2+4) = 23

Solution Approach

A solution to the problem is by storing the subarray sum and then sorting them to find unique once. Then we will consider all unique subarrays for the sum.

Algorithm

Step 1 − Find the sum of all sub-arrays and store it in a vector.

Step 2 − Sort the vector.

Step 3 − Consider all the vectors which are unique and mark the sum of rest to 0.

Step 4 − Calculate and print the sum.

Example

Program to illustrate the working of our solution

#include 
using namespace std;
long int findSumOfSubArraySum(int arr[], int n){
   int i, j;
   long int sumArrayTill[n + 1] = { 0 };
   for (i = 0; i  subArraySum;
   for (i = 1; i 

Output

The sum of all unique subarray sum is 144

Another approach using Iteration

Another approach to solve the problem is using a hash table. We will find the subarray sums and store them in a hash table and increment hash count. Then find the sum of all unique subarrays (subarray with hash count 1).

Example

Program to illustrate the working of our solution

#include 
using namespace std;
long int findSumOfSubArraySum(int arr[], int n){
   int sumSubArraySum = 0;
   unordered_map sumSubArray;
   for (int i = 0; i 

Output

The sum of all unique subarray sum is 124
Updated on: 2022-01-25T14:17:49+05:30

788 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements