Third Maximum Number - Problem
Given an integer array nums, return the third distinct maximum number in this array.
If the third maximum does not exist, return the maximum number.
Note: You must find the third distinct maximum, meaning duplicates are ignored when counting maximums.
Input & Output
Example 1 — Basic Case with Third Maximum
$
Input:
nums = [3,2,1]
›
Output:
1
💡 Note:
Three distinct numbers exist: 3 (first max), 2 (second max), 1 (third max). Return 1.
Example 2 — Less than 3 Distinct Numbers
$
Input:
nums = [1,2]
›
Output:
2
💡 Note:
Only 2 distinct numbers exist. Third maximum doesn't exist, so return the maximum: 2.
Example 3 — Array with Duplicates
$
Input:
nums = [2,2,3,1]
›
Output:
1
💡 Note:
Distinct numbers: 3 (first max), 2 (second max), 1 (third max). Duplicates are ignored. Return 1.
Constraints
- 1 ≤ nums.length ≤ 104
- -231 ≤ nums[i] ≤ 231 - 1
Visualization
Tap to expand
Understanding the Visualization
1
Input Array
Array with possible duplicates: [3, 2, 1]
2
Find Distinct Maximums
Identify the 1st, 2nd, and 3rd largest distinct values
3
Return Result
Return 3rd maximum if exists, else return maximum
Key Takeaway
🎯 Key Insight: Only need to track the top 3 distinct values to determine the third maximum efficiently
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code