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 Swift

1 Answer

0 votes
import Foundation

func maxProductPair(_ nums: [Int]) -> (Int, Int) {
    precondition(nums.count >= 2, "Need at least two numbers")

    var max1 = Int.min
    var max2 = Int.min
    var min1 = Int.max
    var min2 = Int.max

    for n in nums {
        // 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
        }
    }

    return (max1 * max2 >= min1 * min2) ? (max1, max2) : (min1, min2)
}


let nums = [3, 9, 1, 3, 7, 0, 4]

let (a, b) = maxProductPair(nums)

print("Pair: (\(a), \(b)), product = \(a * b)")




/*
run:

Pair: (9, 7), product = 63

*/

 



answered Dec 26, 2025 by avibootz
...