Maximum Product Subarray
Last Updated :
03 Sep, 2024
Given an integer array, the task is to find the maximum product of any subarray.
Examples:
Input: arr[] = {-2, 6, -3, -10, 0, 2}
Output: 180
Explanation: The subarray with maximum product is {6, -3, -10} with product = 6 * (-3) * (-10) = 180
Input: arr[] = {-1, -3, -10, 0, 60}
Output: 60
Explanation: The subarray with maximum product is {60}.
[Naive Approach] By using two nested loops â O(n^2) Time and O(1) Space
The idea is to traverse over every contiguous subarray, find the product of each of these subarrays and return the maximum product among all the subarrays.
C++
// C++ program to find Maximum Product Subarray
// using nested loops
#include <bits/stdc++.h>
using namespace std;
// Function to return the product of max product subarray
long long maxProduct(vector<int> &arr) {
int n = arr.size();
// Initializing result
long long result = arr[0];
for (int i = 0; i < n; i++) {
long long mul = 1;
// traversing in current subarray
for (int j = i; j < n; j++) {
mul *= arr[j];
// updating result every time
// to keep track of the maximum product
result = max(result, mul);
}
}
return result;
}
int main() {
vector<int> arr = { -2, 6, -3, -10, 0, 2 };
cout << maxProduct(arr);
return 0;
}
C
// C program to find Maximum Product Subarray
// using nested loops
#include <stdio.h>
// Function to return the product of max product subarray
long long maxProduct(int arr[], int n) {
// Initializing result
long long result = arr[0];
for (int i = 0; i < n; i++) {
long long mul = 1;
// traversing in current subarray
for (int j = i; j < n; j++) {
mul *= arr[j];
// updating result every time
// to keep track of the maximum product
result = (result > mul) ? result : mul;
}
}
return result;
}
int main() {
int arr[] = { -2, 6, -3, -10, 0, 2 };
int n = sizeof(arr) / sizeof(arr[0]);
printf("%lld\n", maxProduct(arr, n));
return 0;
}
Java
// Java program to find Maximum Product Subarray using
// nested loops
import java.io.*;
class GfG {
// Function to return the product of max product subarray
static long maxProduct(int arr[]) {
int n = arr.length;
// Initializing result
long result = arr[0];
for (int i = 0; i < n; i++) {
long mul = 1;
// traversing in current subarray
for (int j = i; j < n; j++) {
mul *= arr[j];
// updating result every time
// to keep track of the maximum product
result = Math.max(result, mul);
}
}
return result;
}
public static void main(String[] args) {
int arr[] = { -2, 6, -3, -10, 0, 2 };
System.out.println(maxProduct(arr));
}
}
Python
# Python program to find Maximum Product Subarray
# using nested loops
# Function to returns the product of max product subarray
def maxProduct(arr):
n = len(arr)
# Initializing result
result = arr[0]
for i in range(n):
mul = 1
# traversing in current subarray
for j in range(i, n):
mul *= arr[j]
# updating result every time
# to keep track of the maximum product
result = max(result, mul)
return result
if __name__ == "__main__":
arr = [-2, 6, -3, -10, 0, 2]
print(maxProduct(arr))
C#
// C# program to find Maximum Product Subarray
// using nested loops
using System;
class GfG {
// Function to return the product of max product subarray
static long maxProduct(int[] arr) {
int n = arr.Length;
// Initializing result
long result = arr[0];
for (int i = 0; i < n; i++) {
long mul = 1;
// traversing in current subarray
for (int j = i; j < n; j++) {
mul *= arr[j];
// updating result every time
// to keep track of the maximum product
result = Math.Max(result, mul);
}
}
return result;
}
public static void Main(String[] args) {
int[] arr = { -2, 6, -3, -10, 0, 2 };
Console.Write(maxProduct(arr));
}
}
JavaScript
// Javascript program to find Maximum Product Subarray
// using nested loops
// Function to return the product of max product subarray
function maxProduct(arr) {
const n = arr.length;
// Initializing result
let result = arr[0];
for (let i = 0; i < n; i++) {
let mul = BigInt(1);
// Traversing in current subarray
for (let j = i; j < n; j++) {
mul *= arr[j];
// Update result to keep track of the maximum product
if(mul > result)
result = mul;
}
}
return result;
}
const arr = [-2n, 6n, -3n, -10n, 0n, 2n];
console.log(maxProduct(arr).toString());
Time Complexity: O(n^2), where n is the size of array.
Auxiliary Space: O(1)
[Expected Approach 1] Using minimum and maximum product ending at any index – O(n) Time and O(1) Space
Let’s assume that the input array has only positive elements. Then, we can simply iterate from left to right keeping track of the maximum running product ending at any index. The maximum product would be the product ending at the last index. The problem arises when we encounter zero or a negative element.
- If we encounter zero, then all the subarrays containing this zero will have product = 0, so zero simply resets the product of the subarray.
- If we encounter a negative number, we need to keep track of the minimum product as well as the maximum product ending at the previous index. This is because when we multiply the minimum product with a negative number, it can give us the maximum product. So, keeping track of minimum product ending at any index is important as it can lead to the maximum product on encountering a negative number.
Step-by-step algorithm:
- Create 3 variables, currMin, currMax and maxProd initialized to the first element of the array.
- Iterate the indices 0 to N-1 and update the variables:
- currMax = maximum(arr[i], currMax * arr[i], currMin * arr[i])
- currMin= minimum(arr[i], currMax * arr[i], currMin * arr[i])
- update the maxProd with the maximum value for each index.
- Return maxProd as the result.
C++
// C++ program to find Maximum Product Subarray using Minimum
// and Maximum Product ending at every index
#include <bits/stdc++.h>
using namespace std;
// function to find the product of max product subarray
long long maxProduct(vector<int> &arr) {
int n = arr.size();
// max product ending at the current index
long long currMax = arr[0];
// min product ending at the current index
long long currMin = arr[0];
// Initialize overall max product
long long maxProd = arr[0];
// Iterate through the array
for (int i = 1; i < n; i++) {
// Temporary variable to store the maximum product ending
// at the current index
long long temp = max({ arr[i] * 1LL, arr[i] * currMax,
arr[i] * currMin });
// Update the minimum product ending at the current index
currMin = min({ arr[i] * 1LL, arr[i] * currMax,
arr[i] * currMin });
// Update the maximum product ending at the current index
currMax = temp;
// Update the overall maximum product
maxProd = max(maxProd, currMax);
}
return maxProd;
}
int main() {
vector<int> arr = { -2, 6, -3, -10, 0, 2 };
cout << maxProduct(arr);
return 0;
}
C
// C program to find Maximum Product Subarray using Minimum
// and Maximum Product ending at every index
#include <stdio.h>
#include <limits.h>
long long max(long long a, long long b, long long c) {
if (a >= b && a >= c) return a;
if (b >= a && b >= c) return b;
return c;
}
long long min(long long a, long long b, long long c) {
if (a <= b && a <= c) return a;
if (b <= a && b <= c) return b;
return c;
}
// Function to find the product of max product subarray
long long maxProduct(int arr[], int n) {
// max product ending at the current index
long long currMax = arr[0];
// min product ending at the current index
long long currMin = arr[0];
// Initialize overall max product
long long maxProd = arr[0];
// Iterate through the array
for (int i = 1; i < n; i++) {
// Temporary variable to store the maximum product ending at the
// current index
long long temp = max(arr[i] * 1LL, arr[i] * currMax, arr[i] * currMin);
// Update the minimum product ending at the current index
currMin = min(arr[i] * 1LL, arr[i] * currMax, arr[i] * currMin);
// Update the maximum product ending at the current index
currMax = temp;
// Update the overall maximum product
maxProd = max(maxProd, currMax, maxProd);
}
return maxProd;
}
int main() {
int arr[] = { -2, 6, -3, -10, 0, 2 };
int n = sizeof(arr) / sizeof(arr[0]);
printf("%lld\n", maxProduct(arr, n));
return 0;
}
Java
// Java program to find Maximum Product Subarray using Minimum
// and Maximum Product ending at every index
class GfG {
static long max(long a, long b, long c) {
return Math.max(a, Math.max(b, c));
}
static long min(long a, long b, long c) {
return Math.min(a, Math.min(b, c));
}
// Function to find the product of max product subarray
static long maxProduct(int[] arr) {
int n = arr.length;
// max product ending at the current index
long currMax = arr[0];
// min product ending at the current index
long currMin = arr[0];
// Initialize overall max product
long maxProd = arr[0];
// Iterate through the array
for (int i = 1; i < n; i++) {
// Temporary variable to store the maximum product ending
// at the current index
long temp = max(arr[i] * 1L, arr[i] * currMax, arr[i] * currMin);
// Update the minimum product ending at the current index
currMin = min(arr[i] * 1L, arr[i] * currMax, arr[i] * currMin);
// Update the maximum product ending at the current index
currMax = temp;
// Update the overall maximum product
maxProd = Math.max(maxProd, currMax);
}
return maxProd;
}
public static void main(String[] args) {
int[] arr = { -2, 6, -3, -10, 0, 2 };
System.out.println(maxProduct(arr));
}
}
Python
# Python program to find Maximum Product Subarray using Minimum
# Maximum Product ending at every index
# function to find the product of max product subarray.
def max_product(arr):
n = len(arr)
# max product ending at the current index
currMax = arr[0]
# min product ending at the current index
currMin = arr[0]
# Initialize overall max product
maxProd = arr[0]
# Iterate through the array
for i in range(1, n):
# Temporary variable to store the maximum product ending
# at the current index
temp = max(arr[i], arr[i] * currMax, arr[i] * currMin)
# Update the minimum product ending at the current index
currMin = min(arr[i], arr[i] * currMax, arr[i] * currMin)
# Update the maximum product ending at the current index
currMax = temp
# Update the overall maximum product
maxProd = max(maxProd, currMax)
return maxProd
if __name__ == "__main__":
arr = [-2, 6, -3, -10, 0, 2]
print(max_product(arr))
C#
// C# program to find Maximum Product Subarray using Minimum
// and Maximum Product ending at every index
using System;
class GfG {
// Function to find the product of max product subarray
static long MaxProduct(int[] arr) {
int n = arr.Length;
// max product ending at the current index
long currMax = arr[0];
// min product ending at the current index
long currMin = arr[0];
// Initialize overall max product
long maxProd = arr[0];
// Iterate through the array
for (int i = 1; i < n; i++) {
// Temporary variable to store the maximum product ending
// at the current index
long temp = Math.Max(arr[i] * 1L, Math.Max(arr[i] * currMax,
arr[i] * currMin));
// Update the minimum product ending at the current index
currMin = Math.Min(arr[i] * 1L, Math.Min(arr[i] * currMax,
arr[i] * currMin));
// Update the maximum product ending at the current index
currMax = temp;
// Update the overall maximum product
maxProd = Math.Max(maxProd, currMax);
}
return maxProd;
}
static void Main() {
int[] arr = { -2, 6, -3, -10, 0, 2 };
Console.WriteLine(MaxProduct(arr));
}
}
JavaScript
// JavaScript program to find Maximum Product Subarray using
// Minimum and Maximum Product ending at every index
function max(a, b, c) {
return a > b ? (a > c ? a : c) : (b > c ? b : c);
}
function min(a, b, c) {
return a < b ? (a < c ? a : c) : (b < c ? b : c);
}
// Function to find the product of max product subarray
function maxProduct(arr) {
// Initialize the maximum and minimum products ending at
// the current index
let currMax = arr[0];
let currMin = arr[0];
// Initialize the overall maximum product
let maxProd = arr[0];
// Iterate through the array starting from the second element
for (let i = 1; i < arr.length; i++) {
// Calculate potential maximum product at this index
const temp = max(arr[i] * currMax, arr[i] * currMin, arr[i]);
// Update the minimum product ending at the current index
currMin = min(arr[i] * currMax, arr[i] * currMin, arr[i]);
// Update the maximum product ending at the current index
currMax = temp;
// Update the overall maximum product
maxProd = max(maxProd, maxProd, currMax);
}
return maxProd;
}
const arr = [ -2n, 6n, -3n, -10n, 0n, 2n ];
console.log(maxProduct(arr).toString());
Working:
Complexity Analysis:
- Time Complexity: O(n), where n is the size of input array.
- Auxiliary Space: O(1)
[Expected Approach 2] By traversing in both directions – O(n) Time and O(1) Space
We will follow a simple approach that is to traverse from the start and keep track of the running product and if the running product is greater than the max product, then we update the max product. Also, if we encounter ‘0’ then make product of all elements till now equal to 1 because from the next element, we will start a new subarray.
But what is the problem with this approach?
Problem will occur when our array will contain odd no. of negative elements. In that case, we have to reject one negative element so that we can even no. of negative elements and their product can be positive. Now, since subarray should be contiguous so we can’t simply reject any one negative element. We have to either reject the first negative element or the last negative element.
Now, if we traverse from start then only the last negative element can be rejected and if we traverse from the last then the first negative element can be rejected. So we will traverse from both ends and find the maximum product subarray.
C++
// C++ program to find Maximum Product Subarray using
// Traversal From Starting and End of an Array
#include <bits/stdc++.h>
using namespace std;
// function to find the product of max product subarray.
long long maxProduct(vector<int> &arr) {
int n = arr.size();
long long maxProd = INT_MIN;
// leftToRight to store product from left to Right
long long leftToRight = 1;
// rightToLeft to store product from right to left
long long rightToLeft = 1;
for (int i = 0; i < n; i++) {
if (leftToRight == 0)
leftToRight = 1;
if (rightToLeft == 0)
rightToLeft = 1;
// calculate product from index left to right
leftToRight *= arr[i];
// calculate product from index right to left
int j = n - i - 1;
rightToLeft *= arr[j];
maxProd = max({leftToRight, rightToLeft, maxProd});
}
return maxProd;
}
int main() {
vector<int> arr = { -2, 6, -3, -10, 0, 2 };
cout << maxProduct(arr);
return 0;
}
C
// C program to find Maximum Product Subarray using
// Traversal From Starting and End of an Array
#include <stdio.h>
#include <limits.h>
// function to find the product of max product subarray
long long maxProduct(int arr[], int n) {
long long maxProd = LLONG_MIN;
// leftToRight to store product from left to Right
long long leftToRight = 1;
// rightToLeft to store product from right to left
long long rightToLeft = 1;
for (int i = 0; i < n; i++) {
if (leftToRight == 0)
leftToRight = 1;
if (rightToLeft == 0)
rightToLeft = 1;
// calculate product from index left to right
leftToRight *= arr[i];
// calculate product from index right to left
int j = n - i - 1;
rightToLeft *= arr[j];
maxProd = (leftToRight > maxProd ? leftToRight : maxProd);
maxProd = (rightToLeft > maxProd ? rightToLeft : maxProd);
}
return maxProd;
}
int main() {
int arr[] = { -2, 6, -3, -10, 0, 2 };
int n = sizeof(arr) / sizeof(arr[0]);
printf("%lld\n", maxProduct(arr, n));
return 0;
}
Java
// Java program to find Maximum Product Subarray using
// Traversal From Starting and End of an Array
class GfG {
// function to find the product of max product subarray
static long maxProduct(int[] arr) {
int n = arr.length;
long maxProd = Long.MIN_VALUE;
// leftToRight to store product from left to Right
long leftToRight = 1;
// rightToLeft to store product from right to left
long rightToLeft = 1;
for (int i = 0; i < n; i++) {
if (leftToRight == 0)
leftToRight = 1;
if (rightToLeft == 0)
rightToLeft = 1;
// calculate product from index left to right
leftToRight *= arr[i];
// calculate product from index right to left
int j = n - i - 1;
rightToLeft *= arr[j];
maxProd = Math.max(leftToRight,
Math.max(rightToLeft, maxProd));
}
return maxProd;
}
public static void main(String[] args) {
int[] arr = { -2, 6, -3, -10, 0, 2 };
System.out.println(maxProduct(arr));
}
}
Python
# Python program to find Maximum Product Subarray using
# Traversal From Starting and End of an Array
# function to find the product of max product subarray
def maxProduct(arr):
n = len(arr)
maxProd = float('-inf')
# leftToRight to store product from left to Right
leftToRight = 1
# rightToLeft to store product from right to left
rightToLeft = 1
for i in range(n):
if leftToRight == 0:
leftToRight = 1
if rightToLeft == 0:
rightToLeft = 1
# calculate product from index left to right
leftToRight *= arr[i]
# calculate product from index right to left
j = n - i - 1
rightToLeft *= arr[j]
maxProd = max(leftToRight, rightToLeft, maxProd)
return maxProd
arr = [-2, 6, -3, -10, 0, 2]
print(maxProduct(arr))
C#
// C# program to find Maximum Product Subarray using
// Traversal From Starting and End of an Array
using System;
class GfG {
// function to find the product of max product subarray
static long MaxProduct(int[] arr) {
int n = arr.Length;
long maxProd = long.MinValue;
// leftToRight to store product from left to Right
long leftToRight = 1;
// rightToLeft to store product from right to left
long rightToLeft = 1;
for (int i = 0; i < n; i++) {
if (leftToRight == 0)
leftToRight = 1;
if (rightToLeft == 0)
rightToLeft = 1;
// calculate product from index left to right
leftToRight *= arr[i];
// calculate product from index right to left
int j = n - i - 1;
rightToLeft *= arr[j];
maxProd = Math.Max(leftToRight, Math.Max(rightToLeft, maxProd));
}
return maxProd;
}
static void Main() {
int[] arr = { -2, 6, -3, -10, 0, 2 };
Console.WriteLine(MaxProduct(arr));
}
}
JavaScript
// JavaScript program to find Maximum Product Subarray using
// Traversal From Starting and End of an Array
function max(a, b, c) {
return a > b ? (a > c ? a : c) : (b > c ? b : c);
}
function maxProduct(arr) {
const n = arr.length;
let ans = BigInt('-9223372036854775808');
// leftToRight to store product from left to Right
let leftToRight = BigInt(1);
// rightToLeft to store product from right to left
let rightToLeft = BigInt(1);
for (let i = 0; i < n; i++) {
if (leftToRight === BigInt(0))
leftToRight = BigInt(1);
if (rightToLeft === BigInt(0))
rightToLeft = BigInt(1);
// calculate product from index left to right
leftToRight *= BigInt(arr[i]);
// calculate product from index right to left
const j = n - i - 1;
rightToLeft *= BigInt(arr[j]);
ans = max(leftToRight, rightToLeft, ans);
}
return ans.toString();
}
const arr = [-2n, 6n, -3n, -10n, 0n, 2n];
console.log(maxProduct(arr));
Working:
Complexity Analysis:
- Time Complexity: O(n), where n is the size of input array.
- Auxiliary Space: O(1)