dsa · easy

Third Maximum Number

Return the third-largest **distinct** value in nums. If nums has fewer than three distinct values, return the largest value instead. Duplicates count once.

Example

nums = [5, 1, 5, 2]. The distinct values are 5, 2, and 1. The largest is 5, the second is 2, the third is 1 → 1.

nums = [9, 9, 9]. Only one distinct value, so there is no third. Return the maximum → 9.

nums = [-5, -1, -2]. Distinct descending: -1, -2, -5. The third is -5.

## Arguments - nums — array of integers; duplicates are ignored for ranking

Constraints

1 <= nums.length <= 4*10^4 -2^31 <= nums[i] <= 2^31 - 1 Hidden tests include near-max size for this bound; a slower-than-intended solution TLEs.

Examples

Example 1

Input:
[5,1,5,2]

Expected:
1

Example 2

Input:
[9,9,9]

Expected:
9

Example 3

Input:
[-5,-1,-2]

Expected:
-5

Open in the Dojo editor