Write a program in C++ to find the maximum and second maximum in a given unsorted array of integers


Let’s suppose we have given an array of unsorted integers of size N. The task is to find the distinct max and second max element which are present in the array. The array may contain duplicate elements also. So we have to find only distinct elements. For example,

Input-1

N = 5
A[ ] = { 2, 2, 1, 3, 4 }

Output

4 3

Explanation − From the given array, we can see ‘4’ is the maximum and ‘3’ is the second maximum.

Input-2

N = 4
A[ ] = { 1,3,3,2 }

Output

3 2

Explanation − from the given array of size 4, we can see ‘3’ is largest and ‘2’ is second largest so we will return 3 2 as output.

Approach to solve this problem

In the given array of size N, there may be some duplicate elements also. To find the maximum and second maximum element from the array we can initialize two variables that store the max and second max.

Initially, if the current element is greater than the max then we will store the value of it to the max and the value of max(previous) to the second max.

To find the distinct element, we will check whether the current element is equal to max or not. If the current value is not equal to the max and also greater than the second max, then we will replace the previous value of the second max with the current value.

  • Initialize and take input of N size of the array.

  • A function maxAndSecondMax(int arr[], int size) takes an array as input and the size of the array. Which returns the max and second max element of the given array.

  • Iterate over the array elements and find if the current element is greater than the max then store the current value to the max and previous value of max with the second max.

  • Otherwise, if the current value is greater than the second max, then replace the previous value with the current value. Also, the current value should not equal the max.

  • Check if the second max does not contain any value.

  • Return the max and second max as the final Output.

Example

 Live Demo

#include<bits/stdc++.h>
using namespace std;
void maxAndSecondMax(int *arr, int size){
   int max= INT_MIN;
   int s_max= INT_MIN;
   for(int i=0;i<size; ++i){
      if(arr[i] >max){
         s_max= max;
         max= arr[i];
      }
      else if(arr[i]> s_max && arr[i]!= max){
         s_max= arr[i];
      }
   }
   if(s_max==INT_MIN){
      s_max= -1;
   }
   cout<<max<<" "<<s_max;
}
int main(){
   int N= 6;
   int A[N]= {1,3,2,5,6,3};
   maxAndSecondMax(A,N);
   return 0;
}

Output

If we will run the above code, then it will print the output as,

6 5

6 and 5 are the distinct elements in the array which are Maximum and Second maximum.

Updated on: 05-Feb-2021

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements