forked from strivedi4u/hacktoberfest2024
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Second largest element
46 lines (36 loc) · 1.03 KB
/
Second largest element
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
#include <iostream>
#include <vector>
#include <climits> // For INT_MIN
using namespace std;
int getSecondLargest(vector<int> &arr) {
int n = arr.size();
if (n < 2) {
return -1; // Return -1 if there are fewer than two elements
}
int largest = INT_MIN, secondLargest = INT_MIN;
for (int i = 0; i < n; i++) {
if (arr[i] > largest) {
secondLargest = largest;
largest = arr[i];
} else if (arr[i] < largest && arr[i] > secondLargest) {
secondLargest = arr[i];
}
}
return (secondLargest == INT_MIN) ? -1 : secondLargest; // Return -1 if no second largest found
}
int main() {
int N;
cin >> N;
vector<int> A(N);
for (int i = 0; i < N; i++) {
cin >> A[i];
}
int result = getSecondLargest(A);
if (result != -1) {
cout << "Second largest element: " << result << endl;
} else {
cout << "No second largest element found" << endl;
}
return 0;
}
// it clearly tackle out ith all the edge cases