

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- 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
- Related Questions & Answers
- Maximum products of two integers in linear time in JavaScript
- Maximum product of any two adjacent elements in JavaScript
- Maximum Product of Three Numbers in C++
- Find a pair with maximum product in array of Integers in C++
- How to get the product of two integers without using * JavaScript
- Maximum GCD of N integers with given product in C++
- Comparing integers by taking two numbers in JavaScript
- Cartesian product of two sets in JavaScript
- Maximum length product of unique words in JavaScript
- Product of numbers present in a nested array in JavaScript
- Maximum product of two non-intersecting paths in a tree in C++
- Armstrong Numbers between two integers?
- Product of two number using HOC - JavaScript
- Java program to calculate the product of two numbers
- Sum of Two Integers in Python
Advertisements