I am trying to find the second largest element in an array. My code is working for most inputs but for some inputs, it is failing.
Also, if I input [6, 6, 6, 5]
, the program should output 5 as the second largest and not 6.
For [6,6,6,6,6,6,6,6,6,5]
, it is printing 6 instead of 5.
For repeating elements it is giving wrong results.
# Given the participants' score sheet for your University Sports Day, you are required to find the runner-up score.
# You are given scores. Store them in a list and find the score of the runner-up.
if __name__ == '__main__':
n = int(input("Enter the total numbers: "))
arr = list(map(int, input("Enter the numbers: ").split()))
if arr[0] >= arr[1]:
first_max = arr[0]
second_max = arr[1]
else:
first_max = arr[1]
second_max = arr[0]
for i in range(2, n):
if arr[i] > first_max:
second_max = first_max
first_max = arr[i]
elif arr[i] > second_max and arr[i] != first_max:
second_max = arr[i]
print(second_max)
Please, someone, explain the logic behind it.