Return the third distinct maximum number in an array, or the maximum number if fewer than three distinct values exist.
Given an integer array nums, find the third distinct maximum number in the array.
A number is considered distinct if it is different from all previously counted values. If the third distinct maximum does not exist, return the maximum value in the array instead.
The array may contain duplicate values, and duplicates should not affect the distinct ranking.
nums.The array is provided directly as the input collection.
1 <= nums.lengthnums[i] are integersExample 1
Input
nums = [3, 2, 1]
Output
1
Explanation
The distinct values in descending order are 3, 2, 1. The third distinct maximum is 1.
Example 2
Input
nums = [1, 2]
Output
2
Explanation
There are fewer than three distinct values, so return the maximum value, which is 2.
Example 3
Input
nums = [2, 2, 3, 1]
Output
1
Explanation
The distinct values in descending order are 3, 2, 1. The third distinct maximum is 1.
Premium problem context
Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.