
- Javascript Basics Tutorial
- Javascript - Home
- Javascript - Overview
- Javascript - Syntax
- Javascript - Enabling
- Javascript - Placement
- Javascript - Variables
- Javascript - Operators
- Javascript - If...Else
- Javascript - Switch Case
- Javascript - While Loop
- Javascript - For Loop
- Javascript - For...in
- Javascript - Loop Control
- Javascript - Functions
- Javascript - Events
- Javascript - Cookies
- Javascript - Page Redirect
- Javascript - Dialog Boxes
- Javascript - Void Keyword
- Javascript - Page Printing
- JavaScript Objects
- Javascript - Objects
- Javascript - Number
- Javascript - Boolean
- Javascript - Strings
- Javascript - Arrays
- Javascript - Date
- Javascript - Math
- Javascript - RegExp
- Javascript - HTML DOM
- JavaScript Advanced
- Javascript - Error Handling
- Javascript - Validations
- Javascript - Animation
- Javascript - Multimedia
- Javascript - Debugging
- Javascript - Image Map
- Javascript - Browsers
- JavaScript Useful Resources
- Javascript - Questions And Answers
- Javascript - Quick Guide
- Javascript - Functions
- Javascript - Resources
Subarray with the greatest product in JavaScript
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
- Related Articles
- Left right subarray sum product - JavaScript
- JavaScript Program for Maximum Product Subarray
- Find the greatest product of three numbers in JavaScript
- Product of subarray just less than target in JavaScript
- Return the greatest possible product of n numbers from the array in JavaScript
- Maximum Product Subarray in Python
- Maximum length subarray with LCM equal to product in C++
- Maximum Product Subarray | Added negative product case in C++
- Subarray pairs with equal sums in JavaScript
- Longest subarray with unit difference in JavaScript
- Check if subarray with given product exists in an array in Python
- Contiguous subarray with 0 and 1 in JavaScript
- Program to find maximum length of subarray with positive product in Python
- Subarray Product Less Than K in C++
- Program to find out the greatest subarray of a given length in python

Advertisements