Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • DSA
  • Interview Questions on Array
  • Practice Array
  • MCQs on Array
  • Tutorial on Array
  • Types of Arrays
  • Array Operations
  • Subarrays, Subsequences, Subsets
  • Reverse Array
  • Static Vs Arrays
  • Array Vs Linked List
  • Array | Range Queries
  • Advantages & Disadvantages
Open In App
Next Article:
Sum of products of all possible Subarrays
Next article icon

Sum of products of all possible Subarrays

Last Updated : 02 Aug, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

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) + d

Now, 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> 

Output: 
20

 

Time Complexity: O(N)
Auxiliary Space: O(1)

Related Topic: Subarrays, Subsequences, and Subsets in Array


Next Article
Sum of products of all possible Subarrays

J

jyoti369
Improve
Article Tags :
  • Pattern Searching
  • Mathematical
  • DSA
  • Arrays
  • subarray
Practice Tags :
  • Arrays
  • Mathematical
  • Pattern Searching

Similar Reads

    Sum of the products of all possible Subsets
    Given an array of n non-negative integers. The task is to find the sum of the product of elements of all the possible subsets. It may be assumed that the numbers in subsets are small and computing product doesn't cause arithmetic overflow. Example : Input : arr[] = {1, 2, 3} Output : 23 Possible Sub
    4 min read
    Sum of all subarrays of size K
    Given an array arr[] and an integer K, the task is to calculate the sum of all subarrays of size K. Examples: Input: arr[] = {1, 2, 3, 4, 5, 6}, K = 3 Output: 6 9 12 15 Explanation: All subarrays of size k and their sum: Subarray 1: {1, 2, 3} = 1 + 2 + 3 = 6 Subarray 2: {2, 3, 4} = 2 + 3 + 4 = 9 Sub
    11 min read
    Product of all Subarrays of an Array
    Given an array of integers arr of size N, the task is to print products of all subarrays of the array. Examples: Input: arr[] = {2, 4} Output: 64 Here, subarrays are [2], [2, 4], [4] Products are 2, 8, 4 Product of all Subarrays = 64 Input : arr[] = {10, 3, 7} Output : 27783000 Here, subarrays are [
    7 min read
    Sum of bitwise OR of all subarrays
    Given an array of positive integers, find the total sum after performing the bit wise OR operation on all the sub arrays of a given array. Examples: Input : 1 2 3 4 5 Output : 71 Input : 6 5 4 3 2 Output : 84 First initialize the two variable sum=0, sum1=0, variable sum will store the total sum and,
    5 min read
    Sum of products of all possible K size subsets of the given array
    Given an array arr[] of N non-negative integers and an integer 1 ? K ? N. The task is to find the sum of the products of all possible subsets of arr[] of size K. Examples: Input: arr[] = {1, 2, 3, 4}, K = 2 Output: 35 (1 * 2) + (1 * 3) + (1 * 4) + (2 * 3) + (2 * 4) + (3 * 4) = 2 + 3 + 4 + 6 + 8 + 12
    15+ min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences