Find first,second and third highest numbers in an array using java


import java.util.*;
public class Testing {
public static void main(String [] args){
Scanner sc=new Scanner(System.in);
String size=sc.nextLine().trim();
int len=Integer.parseInt(size);
if(len>2){
String arrayElements=sc.nextLine();
String [] array=arrayElements.split(" ");
int firstMax=Integer.parseInt(array[0]);
int secondMax=Integer.parseInt(array[1]);
int thirdMax=Integer.parseInt(array[2]);
for(int i=0;i<array.length;i++){
if(Integer.parseInt(array[i])>firstMax){
thirdMax=secondMax;
secondMax=firstMax;
firstMax=Integer.parseInt(array[i]);
}else if(Integer.parseInt(array[i])>secondMax){
thirdMax=secondMax;
secondMax=Integer.parseInt(array[i]);
System.out.println(secondMax);
}else if(Integer.parseInt(array[i])>thirdMax){
thirdMax=Integer.parseInt(array[i]);
}
}
System.out.print(firstMax+" "+secondMax+" "+thirdMax);
}
else{
System.out.println("Array length must be atleast three or greater");
}
sc.close();
}
}
Input:
7
1 2 3 4 5 6 7

Output:
7 6 5

Input:
7
29 79 17 8 4 9 97

Output:
97 79 29

Comments

Popular posts from this blog

Reasoning-Number Series

Profit and Loss

Reasoning-Letter Series