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
...