-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsecond_largest.java
58 lines (46 loc) · 1.33 KB
/
second_largest.java
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
//{ Driver Code Starts
//Initial Template for Java
import java.util.*;
import java.io.*;
public class Main {
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int tc = Integer.parseInt(br.readLine().trim());
while (tc-- > 0) {
String[] inputLine;
int n = Integer.parseInt(br.readLine().trim());
int[] arr = new int[n];
inputLine = br.readLine().trim().split(" ");
for (int i = 0; i < n; i++) {
arr[i] = Integer.parseInt(inputLine[i]);
}
int ans = new Solution().print2largest(arr, n);
System.out.println(ans);
}
}
}
// } Driver Code Ends
//User function Template for Java
class Solution {
int print2largest(int arr[], int n) {
// code here
Arrays.sort(arr);
int greatest=arr[n-1];
if(n>=2)
{
greatest=arr[n-1];
int secondGreatest=-1;
for(int i=n-1;i>=0;i--)
{
if(arr[i]<greatest)
{
secondGreatest=arr[i];
break;
}
}
return secondGreatest;
}else{
return -1;
}
}
}