Read n numbers and print the second largest different value. If all the numbers are equal, print none.
What to build
A search for the runner-up.
Requirements
- Read the numbers.
- Print the second largest different value, or
none.
Input
The first line has n (2 ≤ n ≤ 100), the second line n whole numbers between -1000000 and 1000000.
Output
The second largest value, or none.
Constraints
n is from 2 to 100.
Example
Input:
5
4 9 2 9 7
Output:
7
Why it works
Equal values are not different, so a value must be strictly less than the largest before it can count as the second largest.
Examples
Example 1 · Input
5 4 9 2 9 7
Expected output
7
Example 2 · Input
3 5 5 5
Expected output
none
Hints
Hint 1
Keep two values: the largest so far and the second largest so far.
Hint 2
A number equal to the largest is not a new second largest.
Hint 3
If every number is the same there is no second largest: print none.
Solution
Show one correct solution (try it yourself first)
#include <stdio.h>
int main(void) {
int n, a[100];
scanf("%d", &n);
for (int i = 0; i < n; i++) scanf("%d", &a[i]);
int best = a[0];
for (int i = 1; i < n; i++)
if (a[i] > best) best = a[i];
int found = 0, second = 0;
for (int i = 0; i < n; i++) {
if (a[i] != best && (!found || a[i] > second)) {
second = a[i];
found = 1;
}
}
if (found) printf("%d\n", second);
else printf("none\n");
return 0;
}