DEV Community

VipulDeshmukh95
VipulDeshmukh95

Posted on

Second Largest Num in Array

Approach:

  1. First got the max num from array.
  2. Using the above max num, got the second max num
  3. If the 2nd Largest num is present, I have returned it.
  4. If such 2nd largest num is absent, I have returned -1.
int Solution::solve(vector<int> &A) {
    int max_num = INT_MIN;
    int max_sec = INT_MIN;
    int n = A.size();


    for(int i = 0; i < n; i++)
    {
        max_num = max(max_num, A[i]);
    }

    for(int i = 0; i < n; i++) 
    {
        if(A[i] != max_num)
        {
          max_sec = max(max_sec, A[i]);
        }
    }

    if(max_sec != INT_MIN)
    {
        return max_sec;
    }
    else{
    return -1;
    }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)