27. Third Maximum Number

EasyArrayArray

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

Input: An integer array nums.

Output: Integer — the third distinct maximum, or maximum if fewer than 3 distinct values.

Examples

Example 1
Input: [3,2,1]
Output: 1
Explanation: Three distinct values: 3,2,1. Third max = 1.
Example 2
Input: [1,2]
Output: 2
Explanation: Only two distinct values. No third max → return maximum = 2.
Example 3
Input: [2,2,3,1]
Output: 1
Explanation: Distinct values: 1,2,3. Third max = 1.

Constraints

Asked by

CognizantAmazonGoogleBloombergMetaMicrosoft
Solve this problem in the editor →