Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,938 questions

51,875 answers

573 users

How to find a pair with maximum product from int array in JavaScript

3 Answers

0 votes
function max_product_from_int_array(arr) { 
    let item1 = arr[0], item2 = arr[1]; 
    let len = arr.length;
     
        for (let i = 0; i < len; i++) {
        for (let j = i + 1; j < len; j++) {
            if (arr[i] * arr[j] > item1 * item2) {
                item1 = arr[i], 
                item2 = arr[j]; 
            }
        }
    }
    
    return [item1, item2];
} 
 
const arr = [3, 9, 1, 3, 7, 0, 4]; 
const rv =  max_product_from_int_array(arr);
const item1 = rv[0];
const item2 = rv[1];
 
console.log(item1 + " " + item2); 
 
 
 
/*
run:
 
9 7 
 
*/

 



answered Apr 16, 2019 by avibootz
edited Dec 26, 2025 by avibootz
0 votes
function maxProductPair(arr) {
  if (!Array.isArray(arr) || arr.length < 2) {
    throw new Error("Array must contain at least two elements.");
  }

  let max1 = -Infinity, max2 = -Infinity;
  let min1 = Infinity, min2 = Infinity;

  for (const x of arr) {

    // Track two largest values
    if (x > max1) {
      max2 = max1;
      max1 = x;
    } else if (x > max2) {
      max2 = x;
    }

    // Track two smallest values
    if (x < min1) {
      min2 = min1;
      min1 = x;
    } else if (x < min2) {
      min2 = x;
    }
  }

  const prodMax = max1 * max2;
  const prodMin = min1 * min2;

  return prodMax >= prodMin
            ? [max1, max2]
            : [min1, min2];
}


const arr = [3, 9, 1, 3, 7, 0, 4]; 

const [a, b] = maxProductPair(arr);

console.log(`Max product pair: ${a}, ${b}`);



/*
run:

Max product pair: 9, 7

*/

 



answered Dec 26, 2025 by avibootz
0 votes
function maxProductPair(nums) {
  if (nums.length < 2) {
    throw new Error("Need at least two numbers");
  }

  const sorted = [...nums].sort((a, b) => a - b);

  const p1 = sorted[sorted.length - 1] * sorted[sorted.length - 2];
  const p2 = sorted[0] * sorted[1];

  return p1 >= p2
    ? [sorted[sorted.length - 1], sorted[sorted.length - 2]]
    : [sorted[0], sorted[1]];
}

 
const arr = [3, 9, 1, 3, 7, 0, 4]; 

console.log(maxProductPair(arr));

 
 
 
/*
run:
 
[ 9, 7 ]
 
*/

 



answered Dec 26, 2025 by avibootz
...