jayati

Second Largest

Jan 6th, 2024
1,144
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.92 KB | None | 0 0
  1. //{ Driver Code Starts
  2. #include <bits/stdc++.h>
  3.  
  4. using namespace std;
  5.  
  6. // } Driver Code Ends
  7. //User function template for C++
  8. class Solution{
  9. public:
  10.     // Function returns the second
  11.     // largest elements
  12.     int print2largest(int arr[], int n) {
  13.         // code here
  14.         sort(arr,arr+n);
  15.         set<int> s;
  16.        
  17.         for(int i=n-1;i>=0;i--)
  18.         {
  19.             s.insert(arr[i]);
  20.         }
  21.         int j=1;
  22.         for (auto i : s)
  23.         {
  24.            if(j==s.size()-1)
  25.            {
  26.                 return i;
  27.            }
  28.            j++;
  29.            
  30.         }
  31.         return -1;
  32.     }
  33. };
  34.  
  35. //{ Driver Code Starts.
  36.  
  37. int main() {
  38.     int t;
  39.     cin >> t;
  40.     while (t--) {
  41.         int n;
  42.         cin >> n;
  43.         int arr[n];
  44.         for (int i = 0; i < n; i++) {
  45.             cin >> arr[i];
  46.         }
  47.         Solution ob;
  48.         auto ans = ob.print2largest(arr, n);
  49.         cout << ans << "\n";
  50.     }
  51.     return 0;
  52. }
  53.  
  54. // } Driver Code Ends
Advertisement
Add Comment
Please, Sign In to add comment