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.

40,023 questions

51,974 answers

573 users

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

2 Answers

0 votes
function maxProductPair(nums: number[]): [number, number] {
  if (nums.length < 2) {
    throw new Error("Need at least two numbers");
  }

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

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

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


const arr: number[] = [0, 9, 5, 6, 7, 8, 1, 2, 4, 3];

console.log(maxProductPair(arr));     
 
 
 
    
/*
run:
    
[9, 8] 
    
*/

 



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

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

  for (const x of nums) {
    if (x > max1) {
      max2 = max1;
      max1 = x;
    } else if (x > max2) {
      max2 = x;
    }

    if (x < min1) {
      min2 = min1;
      min1 = x;
    } else if (x < min2) {
      min2 = x;
    }
  }

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



const arr: number[] = [0, 9, 5, 6, 7, 8, 1, 2, 4, 3];

console.log(maxProductPair(arr));     
 
 
 
    
/*
run:
    
[9, 8] 
    
*/

 



answered Dec 26, 2025 by avibootz
...