- Trending Categories
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
Maximum Product of Two Numbers in a List of Integers in JavaScript
We are required to write a JavaScript function that takes in an array of integers as the first and the only argument.
The function should find the maximum product that can be achieved multiplying any two elements of the array. The condition for us is that we have to do this in linear time and constant space.
For example −
If the input array is −
const arr = [3, 9, 2, 1, 0];
Then the output should be −
const output = 27;
because it’s the greatest product and can be achieved by multiplying 3 and 9.
Example
Following is the code −
const arr = [3, 9, 2, 1, 0]; const maxPairProduct = (arr = []) => { let c = Infinity, d = c; let a = -Infinity - 1, b = a; for (const n of arr) { if(n >= a){ b = a; a = n; }else if(n >= b){ b = n; }; if(n <= d){ c = d; d = n; }else if(n <= c){ c = n; }; }; return Math.max(a * b, c * d); }; console.log(maxPairProduct(arr));
Output
Following is the console output −
27
Advertisements