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
Post a Comment