Number of subarrays for which product and sum are equal

Given a array of n numbers. We need to count the number of subarrays having the product and sum of elements are equal
Examples:

Input  : arr[] = {1, 3. 2}
Output : 4
The subarrays are :
[0, 0] sum = 1, product = 1,
[1, 1] sum = 3, product = 3,
[2, 2] sum = 2, product = 2 and 
[0, 2] sum = 1+3+2=6, product = 1*3*2 = 6

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

The idea is simple, we check for each subarray that if product and sum of its elements are equal or not. If it is then increase the counter variable by 1

// C++ program to count subarrays with
// same sum and product.
#include<bits/stdc++.h>
using namespace std;
// returns required number of subarrays
int numOfsubarrays(int arr[] , int n)
{
    int count = 0; // Initialize result
    // checking each subarray
    for (int i=0; i<n; i++)
    {
        int product = arr[i];
        int sum = arr[i];
        for (int j=i+1; j<n; j++)
        {
            // checking if product is equal
            // to sum or not
            if (product==sum)
                count++;
            product *= arr[j];
            sum += arr[j];
        }
        if (product==sum)
            count++;
    }
    return count;
}
// driver function
int main()
{
    int arr[] = {1,3,2};
    int n = sizeof(arr)/sizeof(arr[0]);
    cout << numOfsubarrays(arr , n);
    return 0;
}

Output:

4

Time Complexity : O(n2)\

Disclaimer: This does not belong to TechCodeBit, its an article taken from the below
source and credits.
source and credits: http://www.geeksforgeeks.org
We have built the accelerating growth-oriented website for budding engineers and aspiring job holders of technology companies such as Google, Facebook, and Amazon
If you would like to study our free courses you can join us at

http://www.techcodebit.com. #techcodebit #google #microsoft #facebook #interview portal #jobplacements
#technicalguide

rakesh

Leave a Reply

Your email address will not be published. Required fields are marked *

Skip to toolbar