# Find Largest and Second Largest number in array and Find Smallest and Second Smallest number in array

Find Largest and Second Largest number in array OR Find the smallest and second smallest element 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
secondMax = value;
}
}

if(secondMax == max){
System.out.println("Largest number : "+max);
}else{
System.out.println("Largest number : "+max);
System.out.println("second largest number :"+secondMax);
}
}
}

```

### Java Program to find Smallest and Second Smallest element in array.

```private static void findSmallestAndSecondSmallestNumberArray(int[] arr){
if(arr==null || arr.length < 2){
System.out.println("Invalid Input");
return;
}

int smallest = arr[0];
int secondSmallest = arr[0];

for (int value : arr) {
if(value < smallest){
secondSmallest = smallest;
smallest = value;

}else if(smallest == secondSmallest || (value < secondSmallest && value != smallest)){
secondSmallest = value;
}
}

if(secondSmallest == smallest){
System.out.println("Smallest number : "+smallest);
}else{
System.out.println("Smallest number : "+smallest);
System.out.println("Second smallest number :"+secondSmallest);
}
}

```

### You may also like to see

#### 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.