Largest product of a subarray of size k

PROBLEM :

Given an array consisting of N positive integers, and an integer k .You have to find the maximum product of k contiguous elements in the array. Your task is to complete the function which takes three arguments .The first argument  is the array A[ ] and second argument is an integer N denoting the size of the array A[ ] and the third argument  is an integer k.The function will return and value denoting the largest product of sub-array of size k.

Input:
The first line of input is an integer T denoting the no of test cases. Then T test cases follow . The first line of each test case are two integer N and K separated by space .The next line contains N space separated values of the array A[ ].

Output:
Output of each test case will be an integer denoting the largest product of subarray of size k.

Constraints:
1<=T<=100
1<=N<=10
1<=K<=N
1<=A[]<=10

Example:
Input
1
4 2
1 2 3 4
Output
12

Explanation:
The sub-array of size 2 will be 3 4 and the product is 12.

--------------------------------------------------------------------------------
SIMPLE c++ IMPLEMENTATION :
--------------------------------------------------------------------------------

/*You are required to complete the function*/

long long max(long long ,long long ) ;

long long findMaxProduct(int A[], int n, int k)
{
    int i,pro,P ;
   
    pro=1 ;
    for(i=0;i<k;i++)
        pro=pro*A[i] ;
   
    P=pro ;  
    for(i=k;i<n;i++)
    {
        P=(P*A[i])/A[i-k] ;
        pro=max(P,pro) ;
    }
    return pro ;
}

long long max(long long a,long long b)
{
    return a>b?a:b ;
}


---------------------------------------------------------------------------------

Comments

Popular posts from this blog

Count ways to N'th Stair(Order does not matter)

Replace all ‘0’ with ‘5’ in an input Integer

Chocolate Distribution Problem

Remove characters from the first string which are present in the second string

Primality Test ( CodeChef Problem code: PRB01 )