Largest product of a subarray of size k - GeeksforGeeks
Given an array consisting of n positive integers, and an integer k. Find the largest product subarray of size k, i.e., find maximum produce of k contiguous elements in the array where k <= n.
Read full article from Largest product of a subarray of size k - GeeksforGeeks
Given an array consisting of n positive integers, and an integer k. Find the largest product subarray of size k, i.e., find maximum produce of k contiguous elements in the array where k <= n.
int
findMaxProduct(
int
arr[],
int
n,
int
k)
{
// Initialize the MaxProduct to 1, as all elements
// in the array are positive
int
MaxProduct = 1;
for
(
int
i=0; i<k; i++)
MaxProduct *= arr[i];
int
prev_product = MaxProduct;
// Consider every product beginning with arr[i]
// where i varies from 1 to n-k-1
for
(
int
i=1; i<=n-k; i++)
{
int
curr_product = (prev_product/arr[i-1]) *
arr[i+k-1];
MaxProduct = max(MaxProduct, curr_product);
prev_product = curr_product;
}
// Return the maximum product found
return
MaxProduct;
}