QUESTION
Given a array of n numbers. We need to count the number of subarrays having the product and sum of elements are equal.
“TESTCASE_1”: “5\n2 1 6 4 8\n###—###SEPERATOR—###—\n5”, “TESTCASE_2”: “8\n1 4 1 1 1 2 5 56\n###—###SEPERATOR—###—\n9”, “TESTCASE_3”: “6\n23 12 45 89 6 3\n###—###SEPERATOR—###—\n6”, “TESTCASE_4”: “9\n1 2 3 4 5 6 7 8 9\n###—###SEPERATOR—###—\n10”, “TESTCASE_5”: “0\n###—###SEPERATOR—###—\n0
ANSWER
import java.io.*;
// Java program to count subarrays with
// same sum and product.
import java.util.*;
class TestClass
{
// returns required number of subarrays
static 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
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int arr[]=new int[n];
for(int i=0;i<n;i++)
arr[i]=sc.nextInt();
System.out.println(numOfsubarrays(arr , n));
}
}