-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path2 Second Largest Element in an Array without sorting.C++
73 lines (64 loc) · 1.66 KB
/
2 Second Largest Element in an Array without sorting.C++
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
//{ Driver Code Starts
// #include <bits/stdc++.h>
#include<iostream>
#include<vector>
#include<algorithm>
#include<string>
using namespace std;
// } Driver Code Ends
// User function template for C++
class Solution {
public:
// Function returns the second
// largest elements
int print2largest(vector<int> &arr) {
//Method -1
// int maximum=0;
// for(int idx=0;idx<arr.size();idx++){
// maximum=max(maximum,arr[idx]);
// }
// int second_largest=-1;
// for(int idx=0;idx<arr.size();idx++){
// if(arr[idx]>second_largest and arr[idx]<maximum){
// second_largest=arr[idx];
// }
// }
// return second_largest;
//Method -2
int max1=arr[0];
int max2=-1;
int temp=0;
for(int idx=1;idx<arr.size();idx++){
if(arr[idx]>max1){
temp=max1;
max1=arr[idx];
max2=temp;
}
if(arr[idx]<max1 && arr[idx]>max2){
max2=arr[idx];
}
}
return max2==max1?-1:max2;
}
};
//{ Driver Code Starts.
int main() {
int t;
cin >> t;
cin.ignore();
while (t--) {
vector<int> arr;
string input;
getline(cin, input);
stringstream ss(input);
int number;
while (ss >> number) {
arr.push_back(number);
}
Solution ob;
int ans = ob.print2largest(arr);
cout << ans << endl;
}
return 0;
}
// } Driver Code Ends