...

/

Solution Review: Finding the Second Maximum Value in an Array

Solution Review: Finding the Second Maximum Value in an Array

This review provides a detailed analysis of the different ways to solve the "Finding the Second Maximum Value in an Array" challenge.

Solution #1: Traversing the array twice

Press + to interact
fn find_second_maximum(arr: &[i32]) -> i32 {
let mut mx = i32::MIN;
let mut second_mx = i32::MIN;
for i in 0..arr.len(){
if arr[i] > mx {
mx = arr[i]
}
}
for i in 0..arr.len(){
if arr[i] > second_mx && arr[i] < mx{
second_mx = arr[i];
}
}
second_mx
}

Traverse the array twice. In the first traversal, you find the maximum element. In the second traversal, you find the greatest element less than the element obtained in the first traversal.

Time complexity

The time complexity of the solution is in O(n) ...

Access this course and 1400+ top-rated courses and projects.