How to find a pair with maximum product from int array in Rust

1 Answer

0 votes
fn max_product_pair(nums: &[i32]) -> (i32, i32) {
    assert!(nums.len() >= 2, "Need at least two numbers");

    let mut max1 = i32::MIN;
    let mut max2 = i32::MIN;
    let mut min1 = i32::MAX;
    let mut min2 = i32::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;
        }
    }

    // Compare products
    if max1 * max2 >= min1 * min2 {
        (max1, max2)
    } else {
        (min1, min2)
    }
}

fn main() {
    let nums = vec![3, 9, 1, 3, 7, 0, 4];
    
    let (a, b) = max_product_pair(&nums);
    
    println!("Pair: ({}, {}), product = {}", a, b, a * b);
}



/*
run:

Pair: (9, 7), product = 63

*/

 



answered Dec 26, 2025 by avibootz
...