Maximum Product Subarray in C++
Last Updated :
26 Jul, 2024
In this article, we will learn how to find the maximum product of a contiguous subarray within a given array of integers. This problem is a variation of the classic "Maximum Subarray Sum" problem and presents an additional challenge because it involves both positive and negative numbers in an array.
Example:
Input:
arr[] = [2, 3, -2, 4]
Output:
6
Explanation: The subarray [2, 3] has the largest product, which is 6.
Approaches to Solve Maximum Product Subarray in C++
Determining the subarray with the highest product involves different strategies. Let's learn these methods using C++.
This method examines every possible subarray and calculates the product of its elements, then returns the highest product found.
Approach:
- Use two nested loops to generate all subarrays.
- Compute the product of elements in each subarray.
- Track and return the maximum product encountered.
Below is the implementation of the above approach in C++.
C++
// C++ program to find the maximum product subarray using
// brute force approach
#include <algorithm>
#include <iostream>
using namespace std;
// Function to find the maximum product subarray
int maxSubarrayProduct(int arr[], int n)
{
// Initialize the result with the first element of the
// array
int result = arr[0];
// Loop through the array to find the maximum product
// subarray
for (int i = 0; i < n; i++) {
int mul = arr[i];
for (int j = i + 1; j < n; j++) {
// Update the result if the current product is
// greater
result = max(result, mul);
mul *= arr[j];
}
// Update the result for the last element of the
// current subarray
result = max(result, mul);
}
return result;
}
int main()
{
// Define the array and its size
int arr[] = { 2, 3, -2, 4 };
int n = sizeof(arr) / sizeof(arr[0]);
// Print the maximum subarray product
cout << "Maximum Subarray Product is "
<< maxSubarrayProduct(arr, n) << endl;
return 0;
}
OutputMaximum Subarray Product is 6
Time Complexity: O(N^2)
Auxiliary Space: O(1)
Kadane’s Algorithm can be modified to track the maximum and minimum products at each position to efficiently find the maximum product subarray.
Approach:
- Initialize max_so_far, max_ending_here, and min_ending_here with the first element.
- Traverse the array, updating these variables based on the current element and the previous values.
- Return max_so_far.
Below is the implementation of the above approach in C++.
C++
// C++ program to find the maximum product subarray using
// Kadane's Algorthm
#include <iostream>
using namespace std;
// Function to find the maximum of two integers
int max(int a, int b) { return (a > b) ? a : b; }
// Function to find the minimum of two integers
int min(int a, int b) { return (a < b) ? a : b; }
// Function to find the maximum of three integers
int maxOfThree(int a, int b, int c)
{
return max(a, max(b, c));
}
// Function to find the minimum of three integers
int minOfThree(int a, int b, int c)
{
return min(a, min(b, c));
}
// Function to find the maximum product subarray
int maxSubarrayProduct(int arr[], int n)
{
// Initialize the variables
int max_ending_here = arr[0];
int min_ending_here = arr[0];
int max_so_far = arr[0];
// Loop through the array to find the maximum product
// subarray
for (int i = 1; i < n; i++) {
// Calculate the maximum and minimum products ending
// at the current index
int temp
= maxOfThree(arr[i], arr[i] * max_ending_here,
arr[i] * min_ending_here);
min_ending_here
= minOfThree(arr[i], arr[i] * max_ending_here,
arr[i] * min_ending_here);
max_ending_here = temp;
// Update the maximum product so far
max_so_far = max(max_so_far, max_ending_here);
}
return max_so_far;
}
// Main function
int main()
{
// Define the array and its size
int arr[] = { 2, 3, -2, 4 };
int n = sizeof(arr) / sizeof(arr[0]);
// Print the maximum subarray product
cout << "Maximum Subarray Product is "
<< maxSubarrayProduct(arr, n) << endl;
return 0;
}
OutputMaximum Subarray Product is 6
Time Complexity: O(N)
Auxiliary Space: O(1)
Method 3: Traversal from Both Ends
This method involves traversing the array from both left and right, keeping track of the maximum product at each step. This can help manage cases where a subarray with a high product spans from one end to the other.
Approach:
- Initialize max_product and current_product with the first element of the array.
- Traverse the array from left to right, updating the current_product and max_product.
- Reset current_product to 1 if it becomes zero or negative.
- Repeat the same process from right to left.
Below is the implementation of the above approach in C++.
C++
// C program to find the maximum product subarray by
// traversing the array from both sides
#include <stdio.h>
// Function to find the maximum of two integers
int max(int a, int b) { return (a > b) ? a : b; }
// Function to find the maximum product subarray
int maxSubarrayProduct(int arr[], int n)
{
// Initialize the variables
int max_product = arr[0];
int current_product = 1;
// Traverse from left to right
for (int i = 0; i < n; i++) {
current_product *= arr[i];
max_product = max(max_product, current_product);
// If current product becomes zero, reset it to 1
if (current_product == 0)
current_product = 1;
}
// Reset current_product for the right-to-left traversal
current_product = 1;
// Traverse from right to left
for (int i = n - 1; i >= 0; i--) {
current_product *= arr[i];
max_product = max(max_product, current_product);
// If current product becomes zero, reset it to 1
if (current_product == 0)
current_product = 1;
}
return max_product;
}
int main()
{
// Define the array and its size
int arr[] = { 2, 3, -2, 4 };
int n = sizeof(arr) / sizeof(arr[0]);
// Print the maximum subarray product
printf("Maximum Subarray Product is %d\n",
maxSubarrayProduct(arr, n));
return 0;
}
OutputMaximum Subarray Product is 6
Time Complexity: O(N)
Auxiliary Space: O(1)
In this method, we maintain two arrays to track the maximum and minimum products ending at each index, which helps handle positive and negative numbers effectively.
Approach:
- Initialize two arrays to store the maximum and minimum products ending at each index.
- Traverse the array, updating the arrays based on the current element and previous values.
- Keep track of the highest product encountered.
Below is the implementation of the above approach in C++.
C++
// C++ program to find the maximum product subarray using
// dynamic programming
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
// Function to find the maximum product subarray
int maxSubarrayProduct(int a[], int size)
{
// Initialize dp arrays for max and min products
vector<int> max_dp(size, 0);
vector<int> min_dp(size, 0);
// Initialize the first element
max_dp[0] = a[0];
min_dp[0] = a[0];
int ans = a[0];
// Traverse the array
for (int i = 1; i < size; i++) {
if (a[i] > 0) {
max_dp[i] = max(a[i], max_dp[i - 1] * a[i]);
min_dp[i] = min(a[i], min_dp[i - 1] * a[i]);
}
else {
max_dp[i] = max(a[i], min_dp[i - 1] * a[i]);
min_dp[i] = min(a[i], max_dp[i - 1] * a[i]);
}
ans = max(ans, max_dp[i]);
}
return ans;
}
int main()
{
// Define the array and its size
int a[] = { 2, 3, -2, 4 };
int n = sizeof(a) / sizeof(a[0]);
// Print the maximum subarray product
cout << "Maximum Subarray Product is "
<< maxSubarrayProduct(a, n) << endl;
return 0;
}
OutputMaximum Subarray Product is 6
Time Complexity: O(N)
Auxiliary Space: O(N)
Similar Reads
Maximum Product Subarray in C In this article, we will learn how to find the product of the maximum product subarray for a given array that contains both positive and negative integers,Example:Input: arr[] = [2, 3, -2, 4]Output: 6Explanation: [2, 3] has the largest product 6.Table of ContentMethod 1: Traversing Over Every Subarr
6 min read
Maximum Subarray Sum in C++ In this article, we will learn how to find the maximum sum of a contiguous subarray within a given array of integers in C++ language. Finding the maximum subarray sum involves determining the contiguous subarray that has the largest sum.Example:Input:arr[] = {-2, 1, -3, 4, -1, 2, 1, -5, 4}Output:6Ex
7 min read
CSES Solutions - Maximum Subarray Sum Given an array arr[] of N integers, your task is to find the maximum sum of values in a contiguous, nonempty subarray. Examples: Input: N = 8, arr[] = {-1, 3, -2, 5, 3, -5, 2, 2}Output: 9Explanation: The subarray with maximum sum is {3, -2, 5, 3} with sum = 3 - 2 + 5 + 3 = 9. Input: N = 6, arr[] = {
5 min read
Largest Sum Contiguous Subarray in C In this article, we will learn how to find the maximum sum of a contiguous subarray for a given array that contains both positive and negative integers in C language.Example:Input: arr = {-2, -3, 4, -1, -2, 1, 5, -3}Output: 7Explanation: The subarray {4,-1, -2, 1, 5} has the largest sum 7.Maximum su
4 min read
array::max_size() in C++ STL Array classes are generally more efficient, light-weight and reliable than C-style arrays. The introduction of array class from C++11 has offered a better alternative for C-style arrays. array::max_size() This function returns the maximum number of elements that the array container can contain. In c
1 min read