Easy
Third Maximum Number
- Time limit
- 1 s
- Memory limit
- 256 MB
- Estimated
- 20 min
- Selection Algorithms
Description
Description
Given an integer array nums, return the third distinct maximum value in the array.
The third distinct maximum is the third-largest value after removing duplicates. If the array contains fewer than three distinct values, return the maximum value instead.
Duplicate values count only once when ranking values.
Examples
Example 1
- Input:
nums = [3, 2, 1] - Output:
1 - Explanation: The distinct values sorted in descending order are
3, 2, 1. The third maximum is1.
Example 2
- Input:
nums = [1, 2] - Output:
2 - Explanation: There are only two distinct values, so the maximum
2is returned.
Example 3
- Input:
nums = [2, 2, 3, 1] - Output:
1 - Explanation: The distinct values are ; the value appears twice but counts once.
Constraints
1 <= nums.length <= 100000-1000000000 <= nums[i] <= 1000000000- Duplicates may appear in the input array.
Sample cases
3Sample 1
Input
nums = [3,2,1]
Expected output
1
Sample 2
Input
nums = [1,2]
Expected output
2
Sample 3
Skills and languages
Patterns
- Top K Elements
Languages
- Python 3
Solve this problem
Create a free account to write, run and submit your solution.
- Write Python or Java in the browser, with your draft saved as you type
- Run your code on the examples as often as you like
- Submit to a sandboxed judge and see exactly which case failed
- Ask the AI mentor for a hint without being handed the answer