Maximum Product Subarray in C
Last Updated :
10 Jul, 2024
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:
6
Explanation: [2, 3] has the largest product 6.
Solving the Maximum Product Subarray problem involves determining the subarray with the maximum product. There are several methods to achieve this in C.
Method 1: Traversing Over Every Subarray
In this method, we traverse over every contiguous subarray, calculate the product of each subarray, and return the maximum product among them.
Approach:
- Run a nested loop to generate every subarray.
- Calculate the product of elements in the current subarray.
- Return the maximum product from these subarrays.
Below is the implementation of the above approach:
C
// C program to find Maximum Product Subarray
#include <stdio.h>
// Find maximum between two numbers.
int max(int num1, int num2)
{
return (num1 > num2) ? num1 : num2;
}
/* Returns the product of max product subarray.*/
int maxSubarrayProduct(int arr[], int n)
{
// Initializing result
int result = arr[0];
for (int i = 0; i < n; i++) {
int mul = arr[i];
// traversing in current subarray
for (int j = i + 1; j < n; j++) {
// updating result every time
// to keep an eye over the maximum product
result = max(result, mul);
mul *= arr[j];
}
// updating the result for (n-1)th index.
result = max(result, mul);
}
return result;
}
int main()
{
// initialize an array
int arr[] = { 2, 3, -2, 4 };
// calculate the size of an array
int n = sizeof(arr) / sizeof(arr[0]);
// print the maximum product of subarray
printf("Maximum Sub array product is %d ",
maxSubarrayProduct(arr, n));
return 0;
}
OutputMaximum Sub array product is 6
Time Complexity: O(N^2)
Auxiliary Space: O(1)
We can use the Kadane’s algorithm with three variables: max_so_far, max_ending_here, and min_ending_here and iterate through the array, updating these variables to find the maximum product subarray.
Approach:
- Use three variables: max_so_far, max_ending_here, and min_ending_here.
- Iterate through the array and update these variables as follows:
- max_ending_here = maximum(arr[i], arr[i] * max_ending_here, arr[i] * min_ending_here)
- min_ending_here = minimum(arr[i], arr[i] * max_ending_here, arr[i] * min_ending_here)
- Update max_so_far with the maximum value for each index.
- Return max_so_far as the result.
Below is the implementation of the above approach:
C
// C program to solve maximum product subarray problem
#include <stdio.h>
// Function to return maximum of two integers
int max(int a, int b)
{
// Return a if a is greater, otherwise return b
return (a > b) ? a : b;
}
// Function to return minimum of two integers
int min(int a, int b)
{
// Return a if a is smaller, otherwise return b
return (a < b) ? a : b;
}
// Function to return maximum of three integers
int maxOfThree(int a, int b, int c)
{
// Return the maximum of the three integers
return max(a, max(b, c));
}
// Function to return minimum of three integers
int minOfThree(int a, int b, int c)
{
// Return the minimum of the three integers
return min(a, min(b, c));
}
// Function to find the maximum product subarray
int maxSubarrayProduct(int arr[], int n)
{
// Initialize the maximum product ending at the first
// element
int max_ending_here = arr[0];
// Initialize the minimum product ending at the first
// element
int min_ending_here = arr[0];
// Initialize the maximum product found so far
int max_so_far = arr[0];
// Iterate through the array from the second element
for (int i = 1; i < n; i++) {
// Calculate the potential maximum and minimum
// products ending at the current element
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 found so far
max_so_far = max(max_so_far, max_ending_here);
}
// Return the maximum product subarray
return max_so_far;
}
int main()
{
// Initialize the array
int arr[] = { 2, 3, -2, 4 };
// Calculate the number of elements in the array
int n = sizeof(arr) / sizeof(arr[0]);
// Print the maximum product of any subarray
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)
Method 3: Using Traversal from Start and End of an Array
In this approach, we traverse the array, multiplying elements. If the current value is greater than the previously stored value, update it. By iterating through the array, we track the maximum product subarray ending at each position.
Approach:
- Initialize two variables: max_product and current_product, both set to the first element of the array.
- Traverse the array from left to right:
- Update current_product by multiplying it with the current element.
- Update max_product by taking the maximum of max_product and current_product.
- If current_product becomes zero or negative, reset it to 1 (since a zero or negative product won’t contribute to the maximum).
- Repeat the same process from right to left, maintaining another current_product and updating max_product.
- Return the final max_product.
Below is the implementation of the above approach:
C
#include <stdio.h>
// Function to return the maximum of two integers
int max(int a, int b) { return (a > b) ? a : b; }
int maxSubarrayProduct(int arr[], int n)
{
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);
// Reset current_product if it becomes zero
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);
// Reset current_product if it becomes zero
if (current_product == 0)
current_product = 1;
}
return max_product;
}
int main()
{
// initialize the array
int arr[] = { 2, 3, -2, 4 };
// calculate the size of the array
int n = sizeof(arr) / sizeof(arr[0]);
// print the maximum product of a subarray
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)
Similar Reads
Maximum Product Subarray in C++
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.
7 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
Subarray meaning in DSA
A subarray is a portion of an array that consists of consecutive elements from the original array. SubarrayCharacteristics 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
2 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
C Program for Maximum sum rectangle in a 2D matrix | DP-27
Write a C program for a given 2D array, the task is to find the maximum sum subarray in it. For example, in the following 2D array, the maximum sum subarray is highlighted with blue rectangle and sum of this subarray is 29. This problem is mainly an extension of the Largest Sum Contiguous Subarray f
6 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