Largest product of a subarray of size k
Last Updated :
07 Nov, 2023
Given an array consisting of n positive integers, and an integer k. Find the largest product subarray of size k, i.e., find the maximum produce of k contiguous elements in the array where k <= n.
Examples :
Input: arr[] = {1, 5, 9, 8, 2, 4,
1, 8, 1, 2}
k = 6
Output: 4608
The subarray is {9, 8, 2, 4, 1, 8}
Input: arr[] = {1, 5, 9, 8, 2, 4, 1, 8, 1, 2}
k = 4
Output: 720
The subarray is {5, 9, 8, 2}
Input: arr[] = {2, 5, 8, 1, 1, 3};
k = 3
Output: 80
The subarray is {2, 5, 8}
Brute Force Approach:
We iterate over all subarrays of size k by using two nested loops. The outer loop runs from 0 to n-k and the inner loop runs from i to i+k-1. We calculate the product of each subarray and update the maximum product found so far. Finally, we return the maximum product.
Here are the steps for above approach:
- Initialize a variable, maxProduct, to INT_MIN, which represents the smallest possible integer value.
- Iterate over all subarrays of size k by using two nested loops.
- The outer loop runs from 0 to n-k.
- The inner loop runs from i to i+k-1, where i is the starting index of the subarray.
- Calculate the product of the current subarray using the inner loop.
- If the product is greater than maxProduct, update maxProduct to the current product.
- Return maxProduct as the result.
Below is the code of above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int findMaxProduct( int arr[], int n, int k)
{
int maxProduct = INT_MIN;
for ( int i = 0; i <= n - k; i++) {
int product = 1;
for ( int j = i; j < i + k; j++) {
product *= arr[j];
}
maxProduct = max(maxProduct, product);
}
return maxProduct;
}
int main()
{
int arr1[] = {1, 5, 9, 8, 2, 4, 1, 8, 1, 2};
int k = 6;
int n = sizeof (arr1)/ sizeof (arr1[0]);
cout << findMaxProduct(arr1, n, k) << endl;
k = 4;
cout << findMaxProduct(arr1, n, k) << endl;
int arr2[] = {2, 5, 8, 1, 1, 3};
k = 3;
n = sizeof (arr2)/ sizeof (arr2[0]);
cout << findMaxProduct(arr2, n, k);
return 0;
}
|
Java
import java.util.Arrays;
public class Main {
static int findMaxProduct( int [] arr, int n, int k) {
int maxProduct = Integer.MIN_VALUE;
for ( int i = 0 ; i <= n - k; i++) {
int product = 1 ;
for ( int j = i; j < i + k; j++) {
product *= arr[j];
}
maxProduct = Math.max(maxProduct, product);
}
return maxProduct;
}
public static void main(String[] args) {
int [] arr1 = { 1 , 5 , 9 , 8 , 2 , 4 , 1 , 8 , 1 , 2 };
int k = 6 ;
int n = arr1.length;
System.out.println(findMaxProduct(arr1, n, k));
k = 4 ;
System.out.println(findMaxProduct(arr1, n, k));
int [] arr2 = { 2 , 5 , 8 , 1 , 1 , 3 };
k = 3 ;
n = arr2.length;
System.out.println(findMaxProduct(arr2, n, k));
}
}
|
Python3
def find_max_product(arr, k):
max_product = float ( '-inf' )
n = len (arr)
for i in range (n - k + 1 ):
product = 1
for j in range (i, i + k):
product * = arr[j]
max_product = max (max_product, product)
return max_product
if __name__ = = "__main__" :
arr1 = [ 1 , 5 , 9 , 8 , 2 , 4 , 1 , 8 , 1 , 2 ]
k = 6
print (find_max_product(arr1, k))
k = 4
print (find_max_product(arr1, k))
arr2 = [ 2 , 5 , 8 , 1 , 1 , 3 ]
k = 3
print (find_max_product(arr2, k))
|
C#
using System;
public class GFG
{
static int FindMaxProduct( int [] arr, int n, int k)
{
int maxProduct = int .MinValue;
for ( int i = 0; i <= n - k; i++)
{
int product = 1;
for ( int j = i; j < i + k; j++)
{
product *= arr[j];
}
maxProduct = Math.Max(maxProduct, product);
}
return maxProduct;
}
public static void Main( string [] args)
{
int [] arr1 = { 1, 5, 9, 8, 2, 4, 1, 8, 1, 2 };
int k = 6;
int n = arr1.Length;
Console.WriteLine(FindMaxProduct(arr1, n, k));
k = 4;
Console.WriteLine(FindMaxProduct(arr1, n, k));
int [] arr2 = { 2, 5, 8, 1, 1, 3 };
k = 3;
n = arr2.Length;
Console.WriteLine(FindMaxProduct(arr2, n, k));
}
}
|
Javascript
function findMaxProduct(arr, k) {
let maxProduct = Number.MIN_VALUE;
const n = arr.length;
for (let i = 0; i <= n - k; i++) {
let product = 1;
for (let j = i; j < i + k; j++) {
product *= arr[j];
}
maxProduct = Math.max(maxProduct, product);
}
return maxProduct;
}
const arr1 = [1, 5, 9, 8, 2, 4, 1, 8, 1, 2];
let k = 6;
console.log(findMaxProduct(arr1, k));
k = 4;
console.log(findMaxProduct(arr1, k));
const arr2 = [2, 5, 8, 1, 1, 3];
k = 3;
console.log(findMaxProduct(arr2, k));
|
Time Complexity: O(n*k), where n is the length of the input array and k is the size of the subarray for which we are finding the maximum product.
Auxiliary Space: O(1), because we are only using a constant amount of additional space to store the maximum product and the product of the current subarray.
Method 2 (Efficient: O(n))
We can solve it in O(n) by using the fact that product of a subarray of size k can be computed in O(1) time if we have product of previous subarray available with us.
curr_product = (prev_product / arr[i-1]) * arr[i + k -1]
prev_product : Product of subarray of size k beginning
with arr[i-1]
curr_product : Product of subarray of size k beginning
with arr[i]
In this way, we can compute the maximum k size subarray product in only one traversal. Below is C++ implementation of the idea.
C++
#include <bits/stdc++.h>
using namespace std;
int findMaxProduct( int arr[], int n, int k)
{
int MaxProduct = 1;
for ( int i=0; i<k; i++)
MaxProduct *= arr[i];
int prev_product = MaxProduct;
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 MaxProduct;
}
int main()
{
int arr1[] = {1, 5, 9, 8, 2, 4, 1, 8, 1, 2};
int k = 6;
int n = sizeof (arr1)/ sizeof (arr1[0]);
cout << findMaxProduct(arr1, n, k) << endl;
k = 4;
cout << findMaxProduct(arr1, n, k) << endl;
int arr2[] = {2, 5, 8, 1, 1, 3};
k = 3;
n = sizeof (arr2)/ sizeof (arr2[0]);
cout << findMaxProduct(arr2, n, k);
return 0;
}
|
Java
import java.io.*;
import java.util.*;
class GFG
{
static int findMaxProduct( int arr[], int n, int k)
{
int MaxProduct = 1 ;
for ( int i= 0 ; i<k; i++)
MaxProduct *= arr[i];
int prev_product = MaxProduct;
for ( int i= 1 ; i<=n-k; i++)
{
int curr_product = (prev_product/arr[i- 1 ]) *
arr[i+k- 1 ];
MaxProduct = Math.max(MaxProduct, curr_product);
prev_product = curr_product;
}
return MaxProduct;
}
public static void main (String[] args)
{
int arr1[] = { 1 , 5 , 9 , 8 , 2 , 4 , 1 , 8 , 1 , 2 };
int k = 6 ;
int n = arr1.length;
System.out.println(findMaxProduct(arr1, n, k));
k = 4 ;
System.out.println(findMaxProduct(arr1, n, k));
int arr2[] = { 2 , 5 , 8 , 1 , 1 , 3 };
k = 3 ;
n = arr2.length;
System.out.println(findMaxProduct(arr2, n, k));
}
}
|
Python3
def findMaxProduct(arr, n, k) :
MaxProduct = 1
for i in range ( 0 , k) :
MaxProduct = MaxProduct * arr[i]
prev_product = MaxProduct
for i in range ( 1 , n - k + 1 ) :
curr_product = (prev_product / / arr[i - 1 ]) * arr[i + k - 1 ]
MaxProduct = max (MaxProduct, curr_product)
prev_product = curr_product
return MaxProduct
arr1 = [ 1 , 5 , 9 , 8 , 2 , 4 , 1 , 8 , 1 , 2 ]
k = 6
n = len (arr1)
print (findMaxProduct(arr1, n, k) )
k = 4
print (findMaxProduct(arr1, n, k))
arr2 = [ 2 , 5 , 8 , 1 , 1 , 3 ]
k = 3
n = len (arr2)
print (findMaxProduct(arr2, n, k))
|
C#
using System;
class GFG
{
static int findMaxProduct( int []arr,
int n, int k)
{
int MaxProduct = 1;
for ( int i = 0; i < k; i++)
MaxProduct *= arr[i];
int prev_product = MaxProduct;
for ( int i = 1; i <= n - k; i++)
{
int curr_product = (prev_product /
arr[i - 1]) *
arr[i + k - 1];
MaxProduct = Math.Max(MaxProduct,
curr_product);
prev_product = curr_product;
}
return MaxProduct;
}
public static void Main ()
{
int []arr1 = {1, 5, 9, 8, 2,
4, 1, 8, 1, 2};
int k = 6;
int n = arr1.Length;
Console.WriteLine(findMaxProduct(arr1, n, k));
k = 4;
Console.WriteLine(findMaxProduct(arr1, n, k));
int []arr2 = {2, 5, 8, 1, 1, 3};
k = 3;
n = arr2.Length;
Console.WriteLine(findMaxProduct(arr2, n, k));
}
}
|
Javascript
<script>
function findMaxProduct(arr, n, k)
{
let MaxProduct = 1;
for (let i = 0; i < k; i++)
MaxProduct *= arr[i];
let prev_product = MaxProduct;
for (let i = 1; i <= n - k; i++)
{
let curr_product =
(prev_product / arr[i - 1]) * arr[i + k - 1];
MaxProduct = Math.max(MaxProduct, curr_product);
prev_product = curr_product;
}
return MaxProduct;
}
let arr1 = [1, 5, 9, 8, 2, 4, 1, 8, 1, 2];
let k = 6;
let n = arr1.length;
document.write(findMaxProduct(arr1, n, k) + "</br>" );
k = 4;
document.write(findMaxProduct(arr1, n, k) + "</br>" );
let arr2 = [2, 5, 8, 1, 1, 3];
k = 3;
n = arr2.length;
document.write(findMaxProduct(arr2, n, k) + "</br>" );
</script>
|
PHP
<?php
function findMaxProduct( $arr , $n , $k )
{
$MaxProduct = 1;
for ( $i = 0; $i < $k ; $i ++)
$MaxProduct *= $arr [ $i ];
$prev_product = $MaxProduct ;
for ( $i = 1; $i < $n - $k ; $i ++)
{
$curr_product = ( $prev_product / $arr [ $i - 1]) *
$arr [ $i + $k - 1];
$MaxProduct = max( $MaxProduct , $curr_product );
$prev_product = $curr_product ;
}
return $MaxProduct ;
}
$arr1 = array (1, 5, 9, 8, 2, 4, 1, 8, 1, 2);
$k = 6;
$n = count ( $arr1 );
echo findMaxProduct( $arr1 , $n , $k ), "\n" ;
$k = 4;
echo findMaxProduct( $arr1 , $n , $k ), "\n" ;
$arr2 = array (2, 5, 8, 1, 1, 3);
$k = 3;
$n = count ( $arr2 );
echo findMaxProduct( $arr2 , $n , $k );
?>
|
Auxiliary Space: O(1), since no extra space is being used.
This article is contributed by Ashutosh Kumar.
Similar Reads
Largest sum subarray of size at least k
Given an array and an integer k, the task is to find the sum of elements of a subarray containing at least k elements which has the largest sum. Examples: Input : arr[] = {-4, -2, 1, -3}, k = 2Output : -1Explanation : The sub array is {-2, 1}. Input : arr[] = {1, 1, 1, 1, 1, 1} , k = 2Output : 6 Exp
14 min read
Length of maximum product subarray
Given an integer array arr[] of size N, the task is to find the maximum length subarray whose products of element is non zero. . Examples: Input: arr[] = [1, 1, 0, 2, 1, 0, 1, 6, 1] Output: 3 Explanation Possible subarray whose product are non zero are [1, 1], [2, 1] and [1, 6, 1] So maximum possibl
8 min read
Maximum product of subsequence of size k
Given an array A[] of n integers, the task is to find a subsequence of size k whose product is maximum among all possible k sized subsequences of the given array. Constraints 1 <= n <= 10^5 1 <= k <= n Examples: Input : A[] = {1, 2, 0, 3}, k = 2 Output : 6 Explanation : Subsequence conta
15 min read
Number of subarrays having product less than K
Given an array of positive numbers, calculate the number of possible contiguous subarrays having product lesser than a given number K. Examples : Input : arr[] = [1, 2, 3, 4] K = 10Output : 7The subarrays are {1}, {2}, {3}, {4}, {1, 2}, {1, 2, 3} and {2, 3} Input : arr[] = [1, 9, 2, 8, 6, 4, 3] K =
13 min read
Maximum number of Perfect Numbers present in a subarray of size K
Given an array arr[ ] consisting of N integers, the task is to determine the maximum number of perfect Numbers in any subarray of size K. Examples: Input: arr[ ] = {28, 2, 3, 6, 496, 99, 8128, 24}, K = 4Output: 3Explanation: The sub-array {6, 496, 99, 8128} has 3 perfect numbers which is maximum. In
10 min read
Bitwise operations on Subarrays of size K
Given an array arr[] of positive integers and a number K, the task is to find the minimum and maximum values of Bitwise operation on elements of subarray of size K. Examples: Input: arr[]={2, 5, 3, 6, 11, 13}, k = 3 Output: Maximum AND = 2 Minimum AND = 0 Maximum OR = 15 Minimum OR = 7 Explanation:
15+ min read
Find maximum product of Bitwise AND and Bitwise OR of K-size subarray
Given an array arr[] containing N integers and an integer K, the task is to find the maximum value of the product of Bitwise AND and Bitwise OR of all elements of a K-sized subarray. Example: Input: arr[] = {1, 2, 3, 4}, K = 2Output: 6Explanation: Bitwise AND and Bitwise XOR of all K-sized subarrays
9 min read
Maximum subarray product modulo M
Given an array, arr[] of size N and a positive integer M, the task is to find the maximum subarray product modulo M and the minimum length of the maximum product subarray. Examples: Input: arr[] = {2, 3, 4, 2}, N = 4, M = 5Output: Maximum subarray product is 4 Minimum length of the maximum product s
8 min read
Find maximum (or minimum) sum of a subarray of size k
Given an array of integers and a number k, find the maximum sum of a subarray of size k. Examples: Input : arr[] = {100, 200, 300, 400}, k = 2Output : 700 Input : arr[] = {1, 4, 2, 10, 23, 3, 1, 0, 20}, k = 4 Output : 39Explanation: We get maximum sum by adding subarray {4, 2, 10, 23} of size 4. Inp
14 min read
Maximum number of Armstrong Numbers present in a subarray of size K
Given an array arr[] consisting of N integers and a positive integer K, the task is to find the maximum count of Armstrong Numbers present in any subarray of size K. Examples: Input: arr[] = {28, 2, 3, 6, 153, 99, 828, 24}, K = 6Output: 4Explanation: The subarray {2, 3, 6, 153} contains only of Arms
12 min read