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 Scala

1 Answer

0 votes
def maxProductPair(nums: Seq[Int]): (Int, Int) = {
  require(nums.length >= 2, "Need at least two numbers")

  var (max1, max2) = (Int.MinValue, Int.MinValue)
  var (min1, min2) = (Int.MaxValue, Int.MaxValue)

  nums.foreach { n =>
    // Track two largest
    if (n > max1) {
      max2 = max1
      max1 = n
    } else if (n > max2) {
      max2 = n
    }

    // Track two smallest
    if (n < min1) {
      min2 = min1
      min1 = n
    } else if (n < min2) {
      min2 = n
    }
  }

  if (max1 * max2 >= min1 * min2) (max1, max2)
  else (min1, min2)
}


val nums = Seq(3, 9, 1, 3, 7, 0, 8, 4)

val (a, b) = maxProductPair(nums)

println(s"Pair: ($a, $b), product = ${a * b}")



/*
run:

Pair: (9, 8), product = 72

*/

 



answered Dec 26, 2025 by avibootz
...