Algorithm Steps
- Given an array of numbers
arr
. - Initialize
max_val
andsecond_max
to-Infinity
. - Iterate through each element in the array.
- If the current element is greater than
max_val
, updatesecond_max
tomax_val
, and then updatemax_val
. - Else if the current element is greater than
second_max
and not equal tomax_val
, updatesecond_max
. - After the loop, return
second_max
.
Find Second Largest using Loop - Optimal Approach Code
def find_second_largest(arr):
max_val = float('-inf')
second_max = float('-inf')
for num in arr:
if num > max_val:
second_max = max_val
max_val = num
elif num > second_max and num != max_val:
second_max = num
return second_max
# Sample Input
arr = [30, 20, 10, 50, 60, 40]
print("Second Largest:", find_second_largest(arr))
Detailed Step by Step Example
Let's find the second largest number in the array using a loop.
Initialize max = -Infinity
and secondMax = -Infinity
.
Check index 0
Current element is 30
. Compare with max = -Infinity
and secondMax = -Infinity
.
30 is greater than current max. Update: secondMax = -Infinity
, max = 30
.
Check index 1
Current element is 20
. Compare with max = 30
and secondMax = -Infinity
.
20 is greater than current secondMax and not equal to max. Update: secondMax = 20
.
Check index 2
Current element is 10
. Compare with max = 30
and secondMax = 20
.
No update required.
Check index 3
Current element is 50
. Compare with max = 30
and secondMax = 20
.
50 is greater than current max. Update: secondMax = 30
, max = 50
.
Check index 4
Current element is 60
. Compare with max = 50
and secondMax = 30
.
60 is greater than current max. Update: secondMax = 50
, max = 60
.
Check index 5
Current element is 40
. Compare with max = 60
and secondMax = 50
.
No update required.
Final Result:
Second Largest Element = 50