use std::error::Error;
/*
Goal:
-----
Find the minimal value of (a[i] + a[j]) for any two distinct elements in a vector.
Efficient Strategy (O(n)):
--------------------------
The smallest possible sum of two distinct elements is obtained by:
- finding the smallest element
- finding the second smallest element
Because any other pair must be >= one of these two.
We scan the vector once, keeping track of:
- min1 = smallest element seen so far
- min2 = second smallest element seen so far
*/
// A function that computes the minimal sum of two distinct elements.
fn minimal_two_sum(vec: &Vec<i32>) -> Result<i32, Box<dyn Error>> {
// Handle edge case: need at least two elements
if vec.len() < 2 {
return Err("Vector must contain at least two elements.".into());
}
// Initialize min1 and min2 to very large values
let mut min1: i32 = i32::MAX;
let mut min2: i32 = i32::MAX;
// Single pass through the vector
for &x in vec.iter() {
if x < min1 {
// x becomes the new smallest; old min1 becomes min2
min2 = min1;
min1 = x;
} else if x < min2 {
// x is not the smallest, but smaller than the second smallest
min2 = x;
}
}
// The minimal sum of two distinct elements
Ok(min1 + min2)
}
fn main() {
let vec: Vec<i32> = vec![7, -3, 10, 1, 5, 2, 4];
match minimal_two_sum(&vec) {
Ok(result) => println!("Minimal sum of two elements: {}", result),
Err(e) => eprintln!("Error: {}", e),
}
}
/*
run:
Minimal sum of two elements: -2
*/