Sum of all Subarrays | Set 1

28 Apr, 2021
Given an integer array ‘arr[]’ of size n, find sum of all sub-arrays of given array. 
Examples : 
Input   : arr[] = {1, 2, 3}
Output  : 20
Explanation : {1} + {2} + {3} + {2 + 3} + 
              {1 + 2} + {1 + 2 + 3} = 20

Input  : arr[] = {1, 2, 3, 4}
Output : 50
Method 1 (Simple Solution) A simple solution is to generate all sub-array and compute their sum.
Below is the implementation of above idea.  
C++
Java
Python3
C#
PHP
Javascript
// Simple C++ program to compute sum of// subarray elements#include<bits/stdc++.h>using namespace std; // Computes sum all sub-arraylong int SubArraySum(int arr[], int n){    long int result = 0,temp=0;     // Pick starting point    for (int i=0; i <n; i++)    {        // Pick ending point        temp=0;        for (int j=i; j<n; j++)        {            // sum subarray between current            // starting and ending points            temp+=arr[j];            result += temp ;        }    }    return result ;} // driver program to test above functionint main(){    int arr[] = {1, 2, 3} ;    int n = sizeof(arr)/sizeof(arr[0]);    cout << "Sum of SubArray : "          << SubArraySum(arr, n) << endl;    return 0;}
// Simple Java program to compute sum of// subarray elementsclass GFG {         // Computes sum all sub-array    public static long SubArraySum(int arr[], int n)    {        long result = 0,temp=0;              // Pick starting point        for (int i = 0; i < n; i ++)        {            // Pick ending point            temp=0;            for (int j = i; j < n; j ++)            {                // sum subarray between current                // starting and ending points                temp+=arr[j];                result += temp ;            }        }        return result ;    }         /* Driver program to test above function */    public static void main(String[] args)    {        int arr[] = {1, 2, 3} ;        int n = arr.length;        System.out.println("Sum of SubArray : " +                          SubArraySum(arr, n));    }}// This code is contributed by Arnav Kr. Mandal.
# Python3 program to compute# sum of subarray elements # Computes sum all sub-arraydef SubArraySum(arr, n):    temp,result = 0,0     # Pick starting point    for i in range(0, n):         # Pick ending point        temp=0;        for j in range(i, n):             # sum subarray between            # current starting and            # ending points            temp+=arr[j]            result += temp    return result # driver programarr = [1, 2, 3]n = len(arr)print ("Sum of SubArray :"       ,SubArraySum(arr, n)) # This code is contributed by# TheGameOf256.
// Simple C# program to compute sum of// subarray elementsusing System; class GFG {         // Computes sum all sub-array    public static long SubArraySum(int []arr,                                      int n)    {        long result = 0,temp=0;             // Pick starting point        for (int i = 0; i < n; i ++)        {            // Pick ending point            temp=0;            for (int j = i; j < n; j ++)            {                                 // sum subarray between current                // starting and ending points                temp+=arr[j];                result += temp ;            }        }        return result ;    }         // Driver Code    public static void Main()    {        int []arr = {1, 2, 3} ;        int n = arr.Length;        Console.Write("Sum of SubArray : " +                        SubArraySum(arr, n));    }} // This code is contributed by nitin mittal
<?php// Simple PHP program to// compute sum of subarray// elements Computes sum// all sub-array function SubArraySum($arr, $n){    $result = 0;    $temp=0;    // Pick starting point    for ($i = 0; $i < $n; $i++)    {        // Pick ending point        $temp=0;        for ($j = $i; $j < $n; $j++)        {            // sum subarray between            // current starting and            // ending points            $temp+=$arr[$j]            $result += $temp ;        }    }    return $result ;} // Driver Code$arr = array(1, 2, 3) ;$n = sizeof($arr);echo "Sum of SubArray : ",    SubArraySum($arr, $n),"\n";     // This code is contributed by ajit?>
<script> // Simple Javascript program to compute sum of// subarray elements // Computes sum all sub-arrayfunction SubArraySum(arr, n){    let result = 0,temp=0;     // Pick starting point    for (let i=0; i <n; i++)    {        // Pick ending point        temp=0;        for (let j=i; j<n; j++)        {            // sum subarray between current            // starting and ending points            temp+=arr[j];            result += temp ;        }    }    return result ;} // driver program to test above function      let arr = [1, 2, 3] ;    let n = arr.length;    document.write("Sum of SubArray : "    + SubArraySum(arr, n) + "<br>");     // This code is contributed by Mayank Tyagi </script>
Output: 
Sum of SubArray : 20
Time Complexity : O(n2) 
Method 2 (efficient solution) If we take a close look then we observe a pattern. Let take an example  
arr[] = [1, 2, 3], n = 3
All subarrays :  [1], [1, 2], [1, 2, 3], 
                 [2], [2, 3], [3]
here first element 'arr[0]' appears 3 times    
     second element 'arr[1]' appears 4 times  
     third element 'arr[2]' appears 3 times

Every element arr[i] appears in two types of subsets:
i)  In subarrays beginning with arr[i]. There are 
    (n-i) such subsets. For example [2] appears
    in [2] and [2, 3].
ii) In (n-i)*i subarrays where this element is not
    first element. For example [2] appears in 
    [1, 2] and [1, 2, 3].

Total of above (i) and (ii) = (n-i) + (n-i)*i 
                            = (n-i)(i+1)
                                  
For arr[] = {1, 2, 3}, sum of subarrays is:
  arr[0] * ( 0 + 1 ) * ( 3 - 0 ) + 
  arr[1] * ( 1 + 1 ) * ( 3 - 1 ) +
  arr[2] * ( 2 + 1 ) * ( 3 - 2 ) 

= 1*3 + 2*4 + 3*3 
= 20
Below is the implementation of above idea. 
C++
Java
Python3
C#
PHP
Javascript
// Efficient C++ program to compute sum of// subarray elements#include<bits/stdc++.h>using namespace std; //function compute sum all sub-arraylong int SubArraySum( int arr[] , int n ){    long int result = 0;     // computing sum of subarray using formula    for (int i=0; i<n; i++)        result += (arr[i] * (i+1) * (n-i));     // return all subarray sum    return result ;} // driver program to test above functionint main(){    int arr[] = {1, 2, 3} ;    int n = sizeof(arr)/sizeof(arr[0]);    cout << "Sum of SubArray : "         << SubArraySum(arr, n) << endl;    return 0;}
// Efficient Java program to compute sum of// subarray elementsclass GFG {         //function compute sum all sub-array    public static long SubArraySum( int arr[] , int n )    {        long result = 0;              // computing sum of subarray using formula        for (int i=0; i<n; i++)            result += (arr[i] * (i+1) * (n-i));              // return all subarray sum        return result ;    }         /* Driver program to test above function */    public static void main(String[] args)    {        int arr[] = {1, 2, 3} ;        int n = arr.length;        System.out.println("Sum of SubArray " +                           SubArraySum(arr, n));    }}// This code is contributed by Arnav Kr. Mandal.
#Python3 code to compute# sum of subarray elements #function compute sum# all sub-arraydef SubArraySum(arr, n ):    result = 0     # computing sum of subarray    # using formula    for i in range(0, n):        result += (arr[i] * (i+1) * (n-i))     # return all subarray sum    return result # driver programarr = [1, 2, 3]n = len(arr)print ("Sum of SubArray : ",      SubArraySum(arr, n)) # This code is contributed by# TheGameOf256.
// Efficient C# program// to compute sum of// subarray elementsusing System; class GFG{             // function compute    // sum all sub-array    public static long SubArraySum(int []arr ,                                   int n )    {        long result = 0;             // computing sum of        // subarray using formula        for (int i = 0; i < n; i++)            result += (arr[i] *                      (i + 1) * (n - i));             // return all subarray sum        return result ;    }         // Driver code    static public void Main ()    {        int []arr = {1, 2, 3} ;        int n = arr.Length;        Console.WriteLine("Sum of SubArray: " +                          SubArraySum(arr, n));    }} // This code is contributed by akt_mit
<?php// Efficient PHP program to compute// sum of subarray elements //function compute sum all sub-arrayfunction SubArraySum($arr , $n){    $result = 0;     // computing sum of subarray    // using formula    for ($i = 0; $i < $n; $i++)        $result += ($arr[$i] *                    ($i + 1) *                    ($n - $i));     // return all subarray sum    return $result ;} // Driver Code$arr = array(1, 2, 3) ;$n = sizeof($arr);echo "Sum of SubArray : ",      SubArraySum($arr, $n) ,"\n";  #This code is contributed by aj_36?>
<script> // Efficient Javascript program// to compute sum of subarray elements // Function compute// sum all sub-arrayfunction SubArraySum(arr, n){    let result = 0;      // Computing sum of    // subarray using formula    for(let i = 0; i < n; i++)        result += (arr[i] * (i + 1) *                            (n - i));      // Return all subarray sum    return result ;} // Driver codelet arr = [ 1, 2, 3 ];let n = arr.length; document.write("Sum of SubArray : " +               SubArraySum(arr, n));                // This code is contributed by divyesh072019 </script>
Output : 
Sum of SubArray : 20
Time complexity : O(n)Reference : https://www.quora.com/Can-we-find-the-sum-of-all-sub-arrays-of-an-integer-array-in-O-n-timeSum of all subsequences of an arrayThis article is contributed by Nishant Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. 
nitin mittal
jit_t
Mohit Chandra
sandydv
panthera_leo
mayanktyagi1709
divyesh072019
Modular Arithmetic
subarray
subarray-sum
Arrays
Mathematical
Arrays
Mathematical
Modular Arithmetic
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to Arrays
Introduction to Data Structures
Python | Using 2D arrays/lists the right way
Find Second largest element in an array
Search an element in a sorted and rotated array
Program for Fibonacci numbers
Set in C++ Standard Template Library (STL)
Write a program to print all permutations of a given string
C++ Data Types
Merge two sorted arrays