Second Largest in array
Second Largest in array
Send Feedback
Second Largest in array
The first line contains an Integer 't' which denotes the number of test cases or queries to be run. Then the test cases follow.
The first line of each test case or query contains an integer 'N' representing the size of the array/list.
The second line contains 'N' single space separated integers representing the elements in the array/list.
For each test case, print the second largest in the array/list if exists, -2147483648 otherwise.
Output for every test case will be printed in a separate line.
1 <= t <= 10^2
0 <= N <= 10^5
Time Limit: 1 sec
1
7
2 13 4 1 3 6 28
13
1
5
9 3 6 2 9
6
2
2
6 6
4
90 8 90 5
-2147483648
8
#include<bits/stdc++.h>int findSecondLargest(int *input, int n){//Write your code hereint first=input[0];int second=INT_MIN;for(int i=1;i<n;i++){if(input[i]>first){second=first;first=input[i];}else if(first>input[i] && input[i]>second) second=input[i];}return second;}
#include <iostream>#include<bits/stdc++.h>using namespace std;
int findSecondLargest(int *input, int n){ //Write your code here int first=input[0]; int second=INT_MIN; for(int i=1;i<n;i++){ if(input[i]>first){ second=first; first=input[i]; } else if(first>input[i] && input[i]>second) second=input[i]; } return second;}
int main(){ int t; cin >> t; while (t--) {
int size; cin >> size; int *input = new int[size];
for (int i = 0; i < size; i++) { cin >> input[i]; }
cout << findSecondLargest(input, size) << endl;
delete[] input; }
return 0;}
Comments
Post a Comment