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 Go

1 Answer

0 votes
package main

import (
    "fmt"
    "math"
)

func maxProductPair(nums []int) (int, int) {
    if len(nums) < 2 {
        panic("need at least two numbers")
    }

    // Track two largest and two smallest numbers
    max1, max2 := math.MinInt, math.MinInt
    min1, min2 := math.MaxInt, math.MaxInt

    for _, n := range nums {
        // Update max values
        if n > max1 {
            max2 = max1
            max1 = n
        } else if n > max2 {
            max2 = n
        }

        // Update min values
        if n < min1 {
            min2 = min1
            min1 = n
        } else if n < min2 {
            min2 = n
        }
    }

    // Compare products
    if max1 * max2 >= min1 * min2 {
        return max1, max2
    }
    
    return min1, min2
}

func main() {
    nums := []int{3, 9, 1, 3, 7, 0, 4}
    
    a, b := maxProductPair(nums)
    
    fmt.Println("Pair with max product:", a, b, "Product:", a*b)
}



/*
run:

Pair with max product: 9 7 Product: 63

*/

 



answered Dec 26, 2025 by avibootz
...