Find Maximum Product Subarray Using JavaScript

In this tutorial we will learn how to Find Maximum Product Subarray from an integer of array. The maximum product subarray is the part or an array which have maximum value of multiplying the subarray elements.
find maximum product subarray
find maximum product subarray

What is Maximum Product Subarray Problem?

Given an array that contains both positive or negative integers. Find the product or the max. product subarray.

let arr = [1, 2, 40, 10, 2, 0, 1, 6, 3, 10]

Solution for this: This problem is solved using JavaScript.

We will use Math.max() and Math.min() to compare the values then find the maximum value from max and min.

Time complexity : o(n)
Aux. Space: o(1)

function maxSubarrayProduct(arr, n)
    let max_ending_here = arr[0];
    let min_ending_here = arr[0];
    // Initialize overall max product
    let max_so_far = arr[0];
    for (let i = 1; i < n; i++)
        let temp = Math.max(Math.max(arr[i], arr[i] * max_ending_here), arr[i] * min_ending_here);
        min_ending_here = Math.min(Math.min(arr[i], arr[i] * max_ending_here), arr[i] * min_ending_here);
        max_ending_here = temp;
        max_so_far = Math.max(max_so_far, max_ending_here);
    return max_so_far;
// Driver code
let arr = [1, 2, 40, 10, 2, 0, 1, 6, 3, 10]
let n = arr.length
console.log("Maximum Sub array product= " + maxSubarrayProduct(arr, n));

You needed to pass and array and length of the array to find the max product of subarray.

This is efficient approach. You can use this with other language also, only the way of declaring of an Array or variable will change.

You can see other examples with other programming languages from here.

Thanks for visiting the tutorial on FlutterTPoint. Please comment for any doubt or query in the comment section below.

result: 1600

Don’t miss new tips!

We don’t spam! Read our [link]privacy policy[/link] for more info.

Leave a Comment