object TwoLargestFinder {
/** A function that finds the two largest elements in a sequence.
* Returns an Option containing a tuple of (largest, second_largest),
* or None if the collection has fewer than 2 elements.
*/
def findTwoLargest(nums: Seq[Int]): Option[(Int, Int)] = {
// Guard clause to ensure safety for collections with fewer than 2 elements
if (nums.length < 2) {
None
} else {
// Initialize the first two elements sorted into (max1, max2)
val initialMax1 = math.max(nums(0), nums(1))
val initialMax2 = math.min(nums(0), nums(1))
// Iterate through the remaining elements in a single O(N) pass using foldLeft
val (largest, secondLargest) = nums.drop(2).foldLeft((initialMax1, initialMax2)) {
case ((m1, m2), x) =>
if (x > m1) {
// New absolute maximum found; previous max1 shifts down to max2
(x, m1)
} else if (x > m2) {
// Greater than second largest, but not the absolute maximum
(m1, x)
} else {
// No change needed
(m1, m2)
}
}
Some((largest, secondLargest))
}
}
def main(args: Array[String]): Unit = {
// Define the sequence with the provided data
val data = Seq(3, 4, 9, 6, 7, 1, 2, 5)
// Call our function and pattern match on the Option result
findTwoLargest(data) match {
case Some((largest, secondLargest)) =>
println(s"Dataset: $data")
println(s"The largest element is: $largest")
println(s"The second largest element is: $secondLargest")
case None =>
println("Error: The collection must contain at least two elements.")
}
}
}
/*
run:
Dataset: List(3, 4, 9, 6, 7, 1, 2, 5)
The largest element is: 9
The second largest element is: 7
*/