DSA problem
Third Maximum Number
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:
1Explanation: The first distinct maximum is 3, the second is 2, and the third is 1.
Example 2
Input:
nums = [1,2]Output:
2Explanation: The third distinct maximum does not exist, so the maximum (2) is returned.
Example 3
Input:
nums = [2,2,3,1]Output:
1Explanation: The first distinct maximum is 3, the second is 2 (the duplicate 2 is ignored), and the third is 1.
Constraints
- 1 <= nums.length <= 10^4
- -2^31 <= nums[i] <= 2^31 - 1
3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.