Given an array arr[] of N positive integers, the task is to find the sum of the product of elements of all the possible subarrays.
Examples:
Input: arr[] = {1, 2, 3}
Output: 20
Explanation: Possible Subarrays are: {1}, {2}, {3}, {1, 2}, {2, 3}, {1, 2, 3}.
Products of all the above subarrays are 1, 2, 3, 2, 6 and 6 respectively.
Sum of all products = 1 + 2 + 3 + 2 + 6 + 6 = 20.Input: arr[] = {1, 2, 3, 4}
Output: 84
Explanation:
Possible Subarrays are: {1}, {2}, {3}, {4}, {1, 2}, {2, 3}, {3, 4}, {1, 2, 3}, {2, 3, 4}, {1, 2, 3, 4}. Products of all the above subarrays are 1, 2, 3, 4, 2, 6, 12, 6, 24 and 24.
Sum of all products = 1 + 2 + 3 + 4 + 2 + 6 + 12 + 6 + 24 + 24 = 84.
Naive Approach: The simplest approach to solve the problem is to generate all possible subarrays and calculate the product of all elements of each subarray and add it to the final sum.Â
Time Complexity: O(N2)
Auxiliary Space: O(1)
Efficient Approach: To optimize the above approach, the idea is to observe the problem into some pattern. Suppose we have four numbers a, b, c, and d. We can write all possible subarrays products as:
a + b + c + d+ ab + bc + cd + abc + bcd + abcd
  = (a + ab + abc + abcd) + (b + bc + bcd) + (c + cd) + d
  = a * (1+ b + bc + bcd) + (b + bc + bcd) + (c + cd) + dNow, the value of underlined expression (b + bc + bcd) can be calculated once and use twice.
Again, (b+ bc + bcd) + (c + cd) = b * (1 + c + cd) + (c + cd)In the same way, the expression (c + cd) can be used twice.
The latter part is the same as above.
Follow the below steps to solve the problem:
- Iterate through the last element and make the reoccurring expression updated with every element and use it further. In this process, update the result accordingly.
- Initialize the ans as 0 that will store the final sum and res as 0 that will keep the track of the value of the product of all elements of the previous subarray.
- Traverse the array from the back and for each element, arr[i] do the following:
- Increment the ans by the product of arr[i] and (1 + res).
- Update res to arr[i]*(1 + res).
- After the above steps, print the sum of the product of all subarrays stored in ans.Â
Below is the implementation of the above approach:
C++14
// C++ program for the above approach #include <bits/stdc++.h> using namespace std; Â
// Function that finds the sum of // products of all subarray of arr[] void sumOfSubarrayProd( int arr[], int n) {          // Stores sum of all subarrays     int ans = 0;     int res = 0; Â
    // Iterate array from behind     for ( int i = n - 1; i >= 0; i--)     {         int incr = arr[i] * (1 + res); Â
        // Update the ans         ans += incr; Â
        // Update the res         res = incr;     } Â
    // Print the final sum     cout << (ans); } Â
// Driver Code int main() { Â Â Â Â Â Â Â Â Â // Given array arr[] Â Â Â Â int arr[] = { 1, 2, 3 }; Â
    // Size of array     int N = sizeof (arr) / sizeof (arr[0]); Â
    // Function call     sumOfSubarrayProd(arr, N); } Â
// This code is contributed by mohit kumar 29 |
Java
// Java program for the above approach Â
import java.io.*; class GFG { Â
    // Function that finds the sum of     // products of all subarray of arr[]     static void sumOfSubarrayProd( int arr[],                                   int n)     {         // Stores sum of all subarrays         int ans = 0 ;         int res = 0 ; Â
        // Iterate array from behind         for ( int i = n - 1 ; i >= 0 ; i--) {             int incr = arr[i] * ( 1 + res); Â
            // Update the ans             ans += incr; Â
            // Update the res             res = incr;         } Â
        // Print the final sum         System.out.println(ans);     } Â
    // Driver Code     public static void main(String[] args)     {         // Given array arr[]         int arr[] = { 1 , 2 , 3 }; Â
        // Size of array         int N = arr.length; Â
        // Function Call         sumOfSubarrayProd(arr, N);     } } |
Python3
# Python3 program for the above approach Â
# Function that finds the sum of # products of all subarray of arr[] def sumOfSubarrayProd(arr, n):          # Stores sum of all subarrays     ans = 0     res = 0 Â
    # Iterate array from behind     i = n - 1     while (i > = 0 ):         incr = arr[i] * ( 1 + res) Â
        # Update the ans         ans + = incr Â
        # Update the res         res = incr         i - = 1 Â
    # Print the final sum     print (ans) Â
# Driver Code if __name__ = = '__main__' : Â Â Â Â Â Â Â Â Â # Given array arr[] Â Â Â Â arr = [ 1 , 2 , 3 ] Â
    # Size of array     N = len (arr) Â
    # Function call     sumOfSubarrayProd(arr, N)      # This code is contributed by ipg2016107 |
C#
// C# program for the // above approach using System; Â
// Function that finds // the sum of products // of all subarray of arr[] class solution{ Â
static void sumOfSubarrayProd( int []arr,                               int n) {     // Stores sum of all   // subarrays   int ans = 0;   int res = 0; Â
  // Iterate array from behind   for ( int i = n - 1; i >= 0; i--)   {     int incr = arr[i] * (1 + res); Â
    // Update the ans     ans += incr; Â
    // Update the res     res = incr;   } Â
  // Print the final sum   Console.WriteLine(ans); } Â
// Driver Code public static void Main(String[] args) {Â Â Â Â Â // Given array arr[] Â Â int []arr = {1, 2, 3 }; Â
  // Size of array   int N = arr.Length;   // Function call   sumOfSubarrayProd(arr, N); } } Â
// This code is contributed by SURENDRA_GANGWAR |
Javascript
<script> // Javascript program to implement // the above approach Â
// Function that finds the sum of     // products of all subarray of arr[]     function sumOfSubarrayProd(arr, n)     {         // Stores sum of all subarrays         let ans = 0;         let res = 0;           // Iterate array from behind         for (let i = n - 1; i >= 0; i--) {             let incr = arr[i] * (1 + res);               // Update the ans             ans += incr;               // Update the res             res = incr;         }           // Print the final sum         document.write(ans);     } Â
    // Driver Code           // Given array arr[]         let arr = [ 1, 2, 3 ];           // Size of array         let N = arr.length;           // Function Call         sumOfSubarrayProd(arr, N);       </script> |
20
Â
Time Complexity: O(N)
Auxiliary Space: O(1)
Related Topic: Subarrays, Subsequences, and Subsets in Array
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!