Skip to content

Commit 9aa8d55

Browse files
committed
Solution to find second largest number in an Array
1 parent 141016a commit 9aa8d55

1 file changed

Lines changed: 36 additions & 0 deletions

File tree

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
package Arrays;
2+
3+
public class SecondLargestNumber {
4+
public static void main(String[] args) {
5+
6+
int [] array = {1, 3, 4, 5, -1, 0};
7+
8+
int length = array.length;
9+
10+
if(length <= 1){
11+
System.out.print("NA");
12+
}
13+
14+
int maximum = 0;
15+
//Find Maximum first
16+
for(int i = 0; i < length; i++){
17+
int element = array[i];
18+
if (element > maximum){
19+
maximum = element;
20+
}
21+
}
22+
23+
System.out.println("Maximum Element is " + maximum);
24+
int secondMaximum = maximum-1;
25+
26+
for(int i = 0; i < length; i++){
27+
int element = array[i];
28+
if ((element < maximum) && (element > secondMaximum)){
29+
secondMaximum = element;
30+
System.out.println("SecondMaximum is " + secondMaximum);
31+
}
32+
}
33+
34+
System.out.print(secondMaximum);
35+
}
36+
}

0 commit comments

Comments
 (0)