easy
0 views
Second Largest Value among N integers
Find and print the second largest integer from a list of N integers.
Understand the Problem
Problem Statement
The program must accept N integers and print the second largest value among the N integers.
Constraints
- 2 ≤ N ≤ 100
- Each integer value will be between -999999 and 999999
- All integers are distinct (no duplicates)
- Input consists of N followed by N integers on separate lines
Examples
Example 1
Input
3
100
2200
345Output
345Explanation
When sorted: [100, 345, 2200]. The second largest value is 345.
Example 2
Input
6
-23
-256
-87
-90
-11019
-2Output
-23Explanation
When sorted: [-11019, -256, -90, -87, -23, -2]. The second largest value is -23.
Solution
#include <stdio.h>
#include <stdlib.h>
int compare(const void *a, const void *b) {
return (*(int*)a - *(int*)b);
}
int main() {
int n;
scanf("%d", &n);
int arr[n];
for(int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
qsort(arr, n, sizeof(int), compare);
printf("%d", arr[n-2]);
return 0;
}Time:O(n log n)
Space:O(n)
Approach:
1. Read N from input using scanf
2. Create an array of size N
3. Read N integers into the array
4. Sort the array using qsort with a comparison function
5. Print the element at index n-2 (second largest)
6. The comparison function ensures ascending order sort
Visual Explanation
Loading diagram...