AlgoInsight

DSA problem

Third Maximum Number

EasyArraysPattern: Array Traversaltop600AmazonGoogleMicrosoftBloomberg

Given an integer array nums, return the third distinct maximum value in the array. If the third maximum does not exist, return the maximum number instead.

Note that "third distinct maximum" means the third largest value among the set of unique values. Duplicates are counted only once, so for [2,2,3,1] the distinct values are {1,2,3} and the third maximum is 1.

Try to solve it in a single pass with constant extra space rather than sorting the whole array.

Examples

Example 1
Input: nums = [3,2,1]
Output: 1
Explanation: The first distinct maximum is 3, the second is 2, and the third is 1.
Example 2
Input: nums = [1,2]
Output: 2
Explanation: The third distinct maximum does not exist, so the maximum (2) is returned.
Example 3
Input: nums = [2,2,3,1]
Output: 1
Explanation: The first distinct maximum is 3, the second is 2 (the duplicate 2 is ignored), and the third is 1.

Constraints

3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.

arraysorting

Browse all DSA problems