Take input a stream of n integer elements, find the second largest element present. The given elements can contain duplicate elements as well. If only 0 or 1 element is given, the second largest should be INT_MIN ( - 2^31 ).

 Take input a stream of n integer elements, find the second largest element present.

The given elements can contain duplicate elements as well. If only 0 or 1 element is given, the second largest should be INT_MIN ( - 2^31 ).

Input format :

Line 1 : Total number of elements (n)

Line 2 : N elements (separated by space)

Sample Input 1:

 4

 3 9 0 9

Sample Output 1:

 3

Sample Input 2 :

 2

 4 4

Sample Output 2:

 -2147483648

Sample Output Explanation:

Since both the elements are equal here, hence second largest element is INT_MIN i.e. ( -2^31 )


Source Code :

Coding Ninjas Solutions
 Take input a stream of n integer elements, find the second largest element present.  The given elements can contain duplicate elements as well. If only 0 or 1 element is given, the second largest should be INT_MIN ( - 2^31 ).


#include<iostream>

using namespace std;

#include <climits>

int main(){

    int n,i;

    cin>>n;

    int a[n];

    int first ,second;

    for(i=0;i<n;i++)

    {

        cin>>a[i];

    }

     if(n<2){

         int b=-2147483648;

         cout<<b;

         return 0;

     }

    first=second=a[0];

    for(i=0;i<n;i++)

    {

        if (a[i]>first)

        {

            second=first;

            first=a[i];

        }

    

     else if(a[i]>second&&a[i]!=first)

     {

         second=a[i];

     }}

       if(second==a[0]&&first==a[0])

       {

           int b=-2147483648;

           cout<<b;

       }

     else{

           cout<<second;

        

          }

    

}


Post a Comment

0 Comments