Second Largest Element
7
2 55 77 88 4 8 99
88
import java.util.Scanner; public class SecondLargest { public static void main(String[] args) { Scanner s = new Scanner(System.in); int n=s.nextInt(); int a[]=new int[n]; for(int i=0;i<n;i++) { a[i]=s.nextInt(); } int sl=secondLargestElement(a); System.out.println(sl); } public static int secondLargestElement(int[] arr) { int l=arr.length; int max=Integer.MIN_VALUE; int secLar=Integer.MIN_VALUE; for(int i=0;i<l;i++) { if(arr[i]>max) { secLar=max; max=arr[i]; } if(arr[i]<max && arr[i]>secLar) { secLar=arr[i]; } } return secLar; } }
Comments
Post a Comment