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 II
Given an array arr[] of N integers, your task is to find the maximum sum of values in a contiguous subarray with length between A and B. Examples: Input: N = 8, A = 1, B = 2, arr[] = {-1, 3, -2, 5, 3, -5, 2, 2}Output: 8Explanation: The subarray with maximum sum is {5, 3}, the length between 1 and 2,
12 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 Size of an Array in C
Array in C is a collection of elements of the same data type that are stored in contiguous memory locations. The size of an array is determined by the number of elements it can store and there is a limit on this size. The maximum size of an array in C is determined by many factors, including the dat
4 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
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
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
Maximum element in a sorted and rotated array
Given a sorted array arr[] (may contain duplicates) of size n that is rotated at some unknown point, the task is to find the maximum element in it. Examples: Input: arr[] = {5, 6, 1, 2, 3, 4}Output: 6Explanation: 6 is the maximum element present in the array.Input: arr[] = {3, 2, 2, 2}Output: 3Expla
7 min read
Generating All Subarrays
Given an array arr[], the task is to generate all the possible subarrays of the given array.Examples: Input: arr[] = [1, 2, 3]Output: [ [1], [1, 2], [2], [1, 2, 3], [2, 3], [3] ]Input: arr[] = [1, 2]Output: [ [1], [1, 2], [2] ]Iterative ApproachTo generate a subarray, we need a starting index from t
8 min read