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 Kotlin

1 Answer

0 votes
fun maxProductPair(nums: IntArray): Pair<Int, Int> {
    require(nums.size >= 2) { "Need at least two numbers" }

    var max1 = Int.MIN_VALUE
    var max2 = Int.MIN_VALUE
    var min1 = Int.MAX_VALUE
    var min2 = Int.MAX_VALUE

    for (n in nums) {
        // Track two largest
        when {
            n > max1 -> {
                max2 = max1
                max1 = n
            }
            n > max2 -> max2 = n
        }

        // Track two smallest
        when {
            n < min1 -> {
                min2 = min1
                min1 = n
            }
            n < min2 -> min2 = n
        }
    }

    return if (max1 * max2 >= min1 * min2) {
        max1 to max2
    } else {
        min1 to min2
    }
}

fun main() {
    val nums = intArrayOf(3, 9, 1, 3, 7, 0, 4)
    
    val (a, b) = maxProductPair(nums)
    
    println("Pair: ($a, $b), product = ${a * b}")
}



/*
run:

Pair: (9, 7), product = 63

*/

 



answered Dec 26, 2025 by avibootz
...