Open In App

Maximum Product Subarray in C++

Last Updated : 26 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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.

Determining the subarray with the highest product involves different strategies. Let's learn these methods using C++.

Method 1: Brute Force Approach

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;
}

Output
Maximum Subarray Product is 6

Time Complexity: O(N^2)
Auxiliary Space: O(1)

Method 2: Kadane’s Algorithm for Maximum Product

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;
}

Output
Maximum 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;
}

Output
Maximum Subarray Product is 6

Time Complexity: O(N)
Auxiliary Space: O(1)

Method 4: Dynamic Programming Approach

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;
}

Output
Maximum Subarray Product is 6

Time Complexity: O(N)
Auxiliary Space: O(N)


Next Article
Article Tags :
Practice Tags :

Similar Reads