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
Third Maximum Number ProblemFind the third distinct maximum, or return the maximum if less than 3 distinct valuesInput Array:321Ranking (Distinct):3211st Max2nd Max3rd MaxSince we have 3 distinct values, return the third maximumOUTPUT1
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
Asked in
Amazon 15 Apple 8 Microsoft 6 Google 4
180.0K Views
Medium Frequency
~15 min Avg. Time
2.1K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen