-
Notifications
You must be signed in to change notification settings - Fork 0
/
SecondLargestElementInArray.java
35 lines (34 loc) · 1.09 KB
/
SecondLargestElementInArray.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
public class SecondLargestElementInArray {
public static void main(String[] args) {
//Optimal
int[] arr = {10, 20, 30, 40, 50};
int largest = arr[0];
int secondLargest = arr[0];
for (int i = 1; i < arr.length; i++) {
if (arr[i] > largest) {
secondLargest = largest;
largest = arr[i];
}
else if (arr[i] > secondLargest && arr[i] > largest) {
secondLargest = arr[i];
}
}
System.out.println("Second largest element in the array is: " + secondLargest);
}
//Brute Force
// public static int secondLargest(int[] arr) {
// int largest = arr[0];
// for (int i = 0; i < arr.length; i++) {
// if (arr[i] > largest) {
// largest = arr[i];
// }
// }
// int slargest = -1;
// for (int i = 0; i < arr.length; i++) {
// if (arr[i] > slargest && arr[i] != largest) {
// slargest = arr[i];
// }
// }
// return slargest;
// }
}