- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
Advertisements
To Continue Learning Please Login
Login with Google