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 Single Pass Tracking Approach INPUT Integer Array: nums 3 index 0 2 index 1 1 index 2 Input Details nums = [3, 2, 1] Length: 3 elements Goal Find 3rd distinct maximum If not found, return max ALGORITHM STEPS 1 Initialize Trackers max1, max2, max3 = -INF 2 Iterate Array Process each num once 3 Update Maximums Shift values accordingly 4 Return Result 3rd max or 1st max Tracking Progress Step max1 max2 max3 num=3 3 - - num=2 3 2 - num=1 3 2 1 3rd max found: 1 FINAL RESULT Third Maximum 1 OK - Found! Explanation Distinct values: {3, 2, 1} Sorted desc: [3, 2, 1] 1st max = 3 2nd max = 2 3rd max = 1 (Answer) Key Insight: Track only 3 maximum values instead of sorting entire array. When a new number exceeds any tracked maximum, shift values down. Skip duplicates to ensure distinct maximums. Complexity Time: O(n) Space: O(1) TutorialsPoint - Third Maximum Number | Single Pass Tracking
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