# Maximum products of two integers in linear time in JavaScript

JavascriptWeb DevelopmentObject Oriented Programming

#### JavaScript for beginners

Best Seller

74 Lectures 10 hours

#### Modern Javascript for Beginners + Javascript Projects

Most Popular

112 Lectures 15 hours

#### The Complete Full-Stack JavaScript Course!

Best Seller

96 Lectures 24 hours

We are required to write a JavaScript function that takes in an array of Numbers with positive as well as negative numbers and returns the maximum products of two numbers in one traversal.

Let's write the code for this function −

## Example

const arr = [-1, -3, -4, 2, 0, -5];
const arr2 = [2, 3, 5, 7, -7, 5, 8, -5];
const produce = arr => arr.reduce((acc, val) => acc*val);
const maximumProduct = (arr = []) => {
const [first] = arr;
if(!first){
return 0;
};
const creds = arr.reduce((acc, val) => {
const { min, max } = acc;
if(val > max){
max = max;
max = val;
return acc;
};
if(val < min){
min = min;
min = val;
return acc;
};
if(val > max){
max = val;
return acc;
};
if(val < min){
min = val;
return acc;
};
return acc;
}, {
min: [first, first],
max: [first, first]
});
const { max, min } = creds;
return produce(max) > produce(min) ? produce(max) : produce(min);
};
console.log(maximumProduct(arr));
console.log(maximumProduct(arr2));

## Output

The output in the console will be −

20
56