Second Largest In Array GFG -Problem
//{ Driver Code Starts
// Initial Template for Java
import java.io.*;
import java.util.*;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(System.in);
int t = Integer.parseInt(sc.nextLine());
while (t-- > 0) {
String[] arr1Str = sc.nextLine().split(" ");
int[] arr = Arrays.stream(arr1Str).mapToInt(Integer::parseInt).toArray();
Solution ob = new Solution();
int ans = ob.getSecondLargest(arr);
System.out.println(ans);
System.out.println("~");
}
}
}
// } Driver Code Ends
// User function Template for Java
class Solution {
public int getSecondLargest(int[] arr) {
// Code Here
int max = Integer.MIN_VALUE, smax = Integer.MIN_VALUE;
for (int num : arr) {
if (num > max) {
smax = max; // Update second max before updating max
max = num; // Update max
}
else if(num >smax && num !=max)
{
smax = num; // Update second max if it's greater than current second max
}
}
if (smax == Integer.MIN_VALUE) {
return -1; // Return -1 if no second max found
} else {
return smax;
}
}
}
Comments
Post a Comment