-
Notifications
You must be signed in to change notification settings - Fork 0
/
Second Largest in array
51 lines (42 loc) · 1.3 KB
/
Second Largest in array
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
problem statment
You have been given a random integer array/list(ARR) of size N. You are required to find and return the second largest element present in the array/list.
Input format :
The first line contains an integer 'N' representing the size of the array/list.
The second line contains 'N' single space separated integers representing the elements in the array/list.
Output Format :
Return the second largest element in the array/list.
Constraints :
0 <= N <= 10^2
1<=arr[i]<=10^3
Time Limit: 1 sec
Sample Input 1:
5
4 3 10 9 2
Sample Output 1:
9
Sample Input 2:
7
13 6 31 14 29 44 3
Sample Output 2:
31
______________________________________________________________
solution are here
def find_second_largest(arr, n):
largest = float('-inf')
second_largest = float('-inf')
for num in arr:
if num > largest:
second_largest = largest
largest = num
elif num != largest and num > second_largest:
second_largest = num
return second_largest
# Read the size of the array/list
n = int(input())
# Read the elements of the array/list
arr = list(map(int, input().split()))
# Find the second largest element
second_largest = find_second_largest(arr, n)
# Print the second largest element
print(second_largest)
______________________________________________