# 414. Third Maximum Number

`Input: nums = [3,2,1]Output: 1Explanation: The third maximum is 1.`
`Input: nums = [1,2]Output: 2Explanation: The third maximum does not exist, so the maximum (2) is returned instead.`
`Input: nums = [2,2,3,1]Output: 1Explanation: Note that the third maximum here means the third maximum distinct number.Both numbers with value 2 are both considered as second maximum.`
`class Solution {public:    int thirdMax(vector<int>& nums) {                sort(nums.begin(), nums.end(), greater<int>());        if(nums.size() < 3){            return nums[0];        }        int m1 = nums[0];        int m2 = nums[1];        int m3 = nums[2];        for(int i=1; i<nums.size(); i++){            if(nums[i] == m1){                if(i+1 < nums.size()){                m2 = nums[i+1];                }            }            if(nums[i] == m2){                if(i+1 < nums.size()){                    m3 = nums[i+1];                }                           }                        if(m1>m2 && m2>m3){                return m3;            }        }                return m1;    }};`

--

--

## More from Andreea

IM rookie

Love podcasts or audiobooks? Learn on the go with our new app.