-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathSecond Largest in array.py
65 lines (50 loc) · 1.88 KB
/
Second Largest in array.py
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
""" -------------------- Second Largest in array -------------------------
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.
If N <= 1 or all the elements are same in the array/list then return -2147483648 or -2 ^ 31(It is the smallest value for the range of Integer)
#### Input format :
The first line contains an Integer 't' which denotes the number of test cases or queries to be run. Then the test cases follow.
First line of each test case or query contains an integer 'N' representing the size of the array/list.
Second line contains 'N' single space separated integers representing the elements in the array/list.
#### Output Format :
For each test case, print the second largest in the array/list if exists, -2147483648 otherwise.
Output for every test case will be printed in a separate line.
#### Constraints :
1 <= t <= 10^2
0 <= N <= 10^5
Time Limit: 1 sec
#### Sample Input:
2
2
6 6
4
90 8 90 5
#### Sample Output :
-2147483648
8
"""
from sys import stdin
MIN_VALUE = -2147483648
def secondLargestElement(arr, n):
if n == 0 :
return MIN_VALUE
largest = arr[0]
secondLargest = MIN_VALUE
for i in range(n) :
if largest < arr[i] :
secondLargest = largest
largest = arr[i]
elif secondLargest < arr[i] and arr[i] != largest :
secondLargest = arr[i]
return secondLargest
def takeInput() :
n = int(stdin.readline().rstrip())
if n != 0:
arr = list(map(int, stdin.readline().rstrip().split(" ")))
return arr, n
return list(), 0
#main
t = int(stdin.readline().rstrip())
while t > 0 :
arr, n = takeInput()
print(secondLargestElement(arr, n))
t -= 1