static int secondLargest(int n,int arr[]){
int max=0,secondmax=-1;
for(int i=0;i<n;i++){
if(arr[i]>max){
max=arr[i];
}
}
for(int i=0;i<n;i++){
if(arr[i]<max && arr[i]>secondmax){
secondmax=arr[i];
}
}
return secondmax;
// Arrays.sort(arr);
// for(int i=1;i<n;i++){
// if(arr[n-i]!=arr[n-i-1]){
// return arr[n-i-1];
// }
// }
// return -1;
}
}
Inputs Can be following
6
12 35 1 10 34 1
or
10
5 5 5 5 5 5 5 5 5 5
New contributor
Rishi Raj is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
1
You can iterate over the array and keep track of the largest and second largest elements:
static int secondLargest(int arr[]) {
// Input sanity
if (arr == null || arr.length < 2) {
throw new IllegalArgumentException("arr must have at least two elements");
}
// Initialization
int max;
int secondmax;
if (arr[0] > arr[1]) {
max = arr[0];
secondmax = arr[1];
} else {
max = arr[1];
secondmax = arr[0];
}
// Go over the rest of the elements
for (int = 2; i < arr.length; ++i) {
int elem = arr[i];
if (elem >= max) {
secondmax = max;
max = elem;
} else if (elem > secondmax) {
secondmax = elem;
}
}
return secondmax;
}
This has an O(n) time complexity and an O(1) space complexity, where n is the length of the array.
I leave you another solution (the time complexity I owe you):
int max = 0, secondmax = 0;
for( int i = 0; i < n; i++ ) {
if( arr[i] > max ) {
// "secondmax" takes the value contained in "max"
secondmax = max;
// "max" takes the value contained in "arr[i]"
max = arr[i] ;
}
else if( arr[i] > secondmax ) {
// "secondmax" takes the value contained in "arr[i]"
secondmax = arr[i];
}
}