Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
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 only argument.
The function should find the maximum product that can be achieved by multiplying any two elements of the array. The condition is that we have to do this in linear time O(n) and constant space O(1).
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.
Approach
The key insight is that the maximum product can come from either:
- Two largest positive numbers
- Two smallest negative numbers (product becomes positive)
We track the two largest and two smallest numbers in a single pass through the array.
Example
const arr = [3, 9, 2, 1, 0];
const maxPairProduct = (arr = []) => {
let c = Infinity, d = c; // Two smallest numbers
let a = -Infinity - 1, b = a; // Two largest numbers
for (const n of arr) {
// Update two largest numbers
if (n >= a) {
b = a;
a = n;
} else if (n >= b) {
b = n;
}
// Update two smallest numbers
if (n <= d) {
c = d;
d = n;
} else if (n <= c) {
c = n;
}
}
// Return maximum of (largest × second largest) or (smallest × second smallest)
return Math.max(a * b, c * d);
};
console.log(maxPairProduct(arr));
27
Example with Negative Numbers
const arr2 = [-5, -3, 2, 1, 4];
console.log("Array:", arr2);
console.log("Maximum product:", maxPairProduct(arr2));
console.log("(-5) × (-3) =", (-5) * (-3)); // Two negatives make positive
console.log("4 × 2 =", 4 * 2); // Two positives
Array: [ -5, -3, 2, 1, 4 ] Maximum product: 15 (-5) × (-3) = 15 4 × 2 = 8
How It Works
The algorithm maintains four variables:
- a, b: Two largest numbers (a ? b)
- c, d: Two smallest numbers (c ? d)
In each iteration, we update these values based on the current number. Finally, we return the maximum of a × b (largest pair) and c × d (smallest pair).
Time and Space Complexity
- Time Complexity: O(n) - single pass through the array
- Space Complexity: O(1) - only four variables used regardless of input size
Conclusion
This solution efficiently finds the maximum product of two numbers by tracking the two largest and two smallest values in a single pass. It handles both positive and negative numbers correctly while maintaining optimal time and space complexity.
