Third Maximum Number in C++


Suppose we have a non-empty array of integers; we have to find the third maximum number in this array. If there is no 3rd max number, then return the maximum one. The challenge is, we have to solve this using linear time complexity.

So, if the input is like [5,3,8,9,1,4,6,2], then the output will be 6.

To solve this, we will follow these steps −

  • initialize a, b, c with NULL

  • for initialize i := 0, when i < size of nums, update (increase i by 1), do −

    • if a is null or nums[i] >= value of a, then −

      • if is not null and nums[i] > value of a, then −

        • c := b, b := a

      • a := nums[i]

    • otherwise when b is null or nums[i] >= value of b, then −

      • if b is not null and nums[i] > value of b, then −

        • c := b

      • b := nums[i]

    • otherwise when c is null or nums[i] >= value of c, then −

      • c := nums[i]

  • return (if c is null, then value of a, otherwise value of c)

Example 

Let us see the following implementation to get better understanding −

 Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
   int thirdMax(vector<int>& nums) {
      int *a, *b, *c;
      a = b = c = NULL;
      for (int i = 0; i < nums.size(); ++i) {
         if (!a || nums[i] >= *a) {
            if (a && nums[i] > *a) {
               c = b;
               b = a;
            }
            a = &nums[i];
         }
         else if (!b || nums[i] >= *b) {
            if (b && nums[i] > *b) {
               c = b;
            }
            b = &nums[i];
         }
         else if (!c || nums[i] >= *c) {
            c = &nums[i];
         }
      }
      return !c ? *a : *c;
   }
};
main(){
   Solution ob;
   vector<int> v = {5,3,8,9,1,4,6,2};
   cout << (ob.thirdMax(v));
}

Input

{5,3,8,9,1,4,6,2}

Output

6

Updated on: 10-Jun-2020

309 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements