problem no 40:(array problem): finding the second largest element in the array.

 QUESTION:

 

Given an array Arr of size N, print second largest element from an array.

Example 1:

Input: 
N = 6
Arr[] = {12, 35, 1, 10, 34, 1}
Output: 34
Explanation: The largest element of the 
array is 35 and the second largest element
is 34.

Example 2:

Input: 
N = 3
Arr[] = {10, 5, 10}
Output: 5
Explanation: The largest element of 
the array is 10 and the second 
largest element is 5.
 
ANSWER:
int print2largest(int arr[], int n) {
    int i;
if (n< 2) {

return -1;
}
sort(arr, arr + n);

for (i = n - 2; i >= 0; i--) 
    {

if (arr[i] != arr[n - 1]) 
        {
return arr[i];

}
}

return -1;
}

 

Comments

Popular posts from this blog

problem 3: given two integers N and M. The problem is to find the number closest to N and divisible by M. If there are more than one such number, then output the one having maximum absolute value.

problem no 7:Given two numbers A and B, find Kth digit from right of AB.

Problem no 16: count the number of squares below N.