Hello Programmers In this post, you will know how to solve the Chef and Subarrays Codechef Solution.
One more thing to add, don’t directly look for the solutions, first try to solve the problems of Codechef by yourself. If you find any difficulty after trying several times, then you can look for solutions.
Problem
Chef likes problems involving arrays. Unfortunately, the last one he tried to solve didn’t quite get solved.
Chef has an array A of N positive numbers. He wants to find the number of subarrays for which the sum and product of elements are equal.
Please help Chef find this number.
Input
The first line of input contains an integer T denoting the number of test cases. T test cases follow. The first line of each test contains the integer N. The next line contains N integers — A1, A2, …, AN — denoting the array.
Output
For each test case, output a single line with the answer for the instance.
Constraints
- 1 ≤ T ≤ 50
- 1 ≤ n ≤ 50
- 1 ≤ Ai ≤ 109
- A1 * A2 * … * An ≤ 109
Example
Input: 3 3 1 3 2 4 4 1 2 1 6 1 2 2 2 2 1 Output: 4 5 9
Explanation:
Example case 1. There are 4 such subarrays: A[1..1], A[2..2], A[3..3], A[1..3]. Consider A[1..3], sum = 1 + 3 + 2 = 6, product = 1 * 3 * 2 = 6.
Chef and Subarrays CodeChef Solutions in JAVA
import java.util.*; import java.lang.*; import java.io.*; import java.math.BigInteger; /* Name of the class has to be "Main" only if the class is public. */ class Codechef { public static void main (String[] args) throws java.lang.Exception { Scanner ip = new Scanner(System.in); int t = ip.nextInt(); for(int u=0;u<t;u++) { int n = ip.nextInt(); int[] a = new int[n]; for(int i=0;i<n;i++) a[i] = ip.nextInt(); int s=0; int p=1; int c=0; for(int i=0;i<n;i++) { s=0; p=1; for(int j=i;j<n;j++) { s = s + a[j]; p = p*a[j]; if(s==p) c++; } } System.out.println(c); } } }
Chef and Subarrays CodeChef Solutios in CPP
#include <iostream> using namespace std; int main() { // your code goes here int t; cin>>t; while(t--){ int n,c=0; cin>>n; long long int a[n]; for(int i=0;i<n;i++){ cin>>a[i]; } for(int i=0;i<n;i++){ int s=0,p=1; for(int j=i;j<n;j++){ s=s+a[j]; p=p*a[j]; if(s==p){ c++; } } } cout<<c; printf("\n"); } return 0; }
Chef and Subarrays CodeChef Solutions in Python
for _ in range(int(input())): n=int(input()) arr=list(map(int,input().split())) new=[] c=0 for i in range(len(arr)+1): for j in range(i+1,len(arr)+1): new.append(arr[i:j]) for x in new: s=0 p=1 for y in x: s+=y p*=y if(s==p): c+=1 #print(new) print(c)
Disclaimer: The above Problem (Chef and Subarrays) is generated by CodeChef but the solution is provided by BrokenProgrammers. This tutorial is only for Educational and Learning purpose.
Note:- I compile all programs, if there is any case program is not working and showing an error please let me know in the comment section. If you are using adblocker, please disable adblocker because some functions of the site may not work correctly.