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 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:6
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
Maximum circular subarray sum of size K
Given an array arr of size N and an integer K, the task is to find the maximum sum subarray of size k among all contiguous sub-array (considering circular subarray also). Examples: Input: arr = {18, 4, 3, 4, 5, 6, 7, 8, 2, 10}, k = 3 Output: max circular sum = 32 start index = 9 end index = 1 Explan
6 min read
Subarray meaning in DSA
A subarray is a portion of an array that consists of consecutive elements from the original array. Characteristics of a Subarray:Contiguity: The elements in a subarray are contiguous, meaning they are consecutive and in order in the original array.Length: The length of a subarray can be any positive
2 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. Table o
4 min read
Longest subarray with given conditions
Given 2 integers S and K and an array arr[] of N integers, find the longest subarray in arr[] such that the subarray can be divided into at most K contiguous segments and the sum of elements of each segment can be at most S. Example: Input: n = 5, k = 2, s = 5, arr = { 1, 3, 2, 1, 5 }Output: 4Explan
9 min read
std::max in C++
The std::max() is the built-in function in C++ used for finding the maximum among two or more elements passed to it as arguments. It is defined inside <algorithm> header file. In this article, we will learn how to use std::max() function in C++. The std::max() can be used in the following ways
3 min read
Minimum and Maximum of all subarrays of size K using Map
Given an array arr[] of N integers and an integer K, the task is to find the minimum and maximum of all subarrays of size K. Examples: Input: arr[] = {2, -2, 3, -9, -5, -8}, K = 4 Output: -9 3 -9 3 -9 3 Explanation: Below are the subarray of size 4 and minimum and maximum value of each subarray: 1.
9 min read
Number of subarrays with GCD equal to 1 in O(n) time
Given an array arr[] of size N, the task is to find the maximum number of sub-arrays such that the GCD(Greatest Common Factor) of all elements of each sub-array is equal to 1 in O(n). Examples: Input: arr[] = {4, 2, 3, 0, 1, 8, 16, 1}.Output: 3Explanation: GCD of subarray {4, 2, 3} is 1, GCD of suba
6 min read
Maximum size subset with given sum using Backtracking
Given an array arr[] consisting of N integers and an integer K, the task is to find the length of the longest subsequence with a sum equal to K.Examples: Input: arr[] = {-4, -2, -2, -1, 6}, K = 0 Output: 3 Explanation: The longest subsequence is of length 3 which is {-4, -2, 6} having sum 0.Input: a
9 min read