Subarray with the greatest product in JavaScript

JavascriptWeb DevelopmentFront End Technology

We are required to write a JavaScript function that takes in an array of integers (positive and negative) as the first and the only argument. The function should find out and return the product of subarray where its maximum.

For example −

If the input array is −

const arr = [4, -5, 2, -3, 1, -4, 0, -3];

Then the output should be −

const output = 120

because the subarray with maximum product is [4, -5, 2, -3]

Example

Following is the code −

const arr = [4, -5, 2, -3, 1, -4, 0, -3];
const maxProduct = (arr = []) => {
   if (arr.length === 0){
      return 0;
   };
   let max = arr[0],
   min = arr[0],
   greatest = arr[0];
   for (let i = 1; i <= arr.length - 1; i++) {
      let tempMax = max * arr[i];
      max = Math.max(
         arr[i],
         Math.max(min * arr[i], max * arr[i])
      );
      min = Math.min(arr[i], Math.min(min * arr[i], tempMax));
      greatest = Math.max(greatest, max);
   }
   return greatest;
};
console.log(maxProduct(arr));

Output

Following is the console output −

120
raja
Published on 19-Jan-2021 06:30:17
Advertisements