![]() |
VOOZH | about |
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 [10], [10, 3], [10, 3, 7], [3], [3, 7], [7]
Products are 10, 30, 210, 3, 21, 7
Product of all Subarrays = 27783000
Naive Approach: A simple solution is to generate all sub-array and compute their product.
27783000
Time Complexity: O(n3)
Auxiliary Space: O(1)
Efficient Approach: An efficient approach is to use two loops and calculate the products while traversing the subarrays.
Below is the implementation of the above approach:
27783000
Time Complexity: O(n2)
Auxiliary Space: O(1)