Second Largest Element

 

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)

Sample Input 1:
7
2 55 77 88 4 8 99
Sample Output 1:
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

Popular posts from this blog

Minimum Length Word

Check Number Sequence