Find Largest and Second Largest number in array

Find Largest and Second Largest number in array

Given a integer array, find largest and second largest number in array. Lets understand the problem statement graphically and it will be more clear,


Algorithm


There are many approach to solve this problem, Lets see one of the efficient way.
  1. Take 2 variable "max" and "secondMax" and initialize both to first element of array.
    int max = arr[0]
    int secondMax = arr[0]
  2. Iterate through array and for each value of array, check,
    • if the current value in array is > "max" then update "secondMax" with "max" value and "max" with new maimum value found.
    • if the current value in array is < "max" but > then "secondMax" then update "secondMax" with new second largest element found.

Java Program to find Largest and Second Largest element in array.


public class FindSecondLargestNumberArray {

 public static void main(String[] args) {
  int[] arr = new int[]{1,1,3,1,5,4};
  findLargestAndSecondLargestNumberArray(arr);
 }
 
 private static void findLargestAndSecondLargestNumberArray(int[] arr){
  if(arr==null || arr.length < 2){
   System.out.println("Invalid Input");
   return;
  }
  
  int max = arr[0];
  int secondMax = arr[0];
  
  for (int value : arr) {
   if(value > max){
    secondMax = max;
    max = value;
   
   }else if(max == secondMax || (value > secondMax && value != max)){
    //value != max condition is required for [1,9,9] kind of array, 
    //where secondMax is 1, but if we don't add this condition then 
    //it will set secondMax not found.
    secondMax = value;
   }
  }
 
  if(secondMax == max){
   System.out.println("Largest number : "+max);
   System.out.println("second largest number : not found");
  }else{
   System.out.println("Largest number : "+max);
   System.out.println("second largest number :"+secondMax);
  }
 }
}


You may also like to see


Find Largest and Smallest number in Array

Count zeros in a row wise and column wise sorted matrix

Find middle element of a linked list

Union and Intersection of Two Sorted Arrays

Merge two sorted arrays in Java

How is ambiguous overloaded method call resolved in java


Enjoy !!!! 

If you find any issue in post or face any error while implementing, Please comment.

Post a Comment