JavaScript most important question and answer(2024)
2nd Largest from an array
Given an unsorted array of size N
with distinct elements. Find the 2nd largest element from the array without sorting the array.
Input Format
The first line contains a single integer N
.
The second line consists of N
integers of the array.
Output Format
Print the second largest number in the new line.
Example 1
Input
6
3 2 1 5 6 4
Output
5
SOURCE CODE
function SecondLargest(arr, n) {
// Write code here
//here find the largest element
let maxElement=-Infinity;
for(let i=0;i<arr.length;i++){
if(arr[i]>maxElement){
maxElement=arr[i];
}
}
let secondMaxElement=-Infinity;
for(let i=0;i<arr.length;i++){
if(arr[i]!=maxElement && arr[i]>secondMaxElement){
secondMaxElement=arr[i];
}
}
console.log(secondMaxElement);
}