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,
There are many approach to solve this problem, Lets see one of the efficient way.
Given a integer array, find largest and second largest number in array.
Lets understand the problem statement graphically and it will be more clear,
Find the largest and second largest element in an array |
Algorithm
There are many approach to solve this problem, Lets see one of the efficient way.
- Take 2 variable "max" and "secondMax" and initialize both to first element of array.
int max = arr[0]
int secondMax = arr[0] - 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.
package javabypatel; 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.
No comments:
Post a Comment