Back to Problem
Official
462 views
Editorial: Third Distinct Maximum
by admin ·
40
1 Intuition
Keep only the three largest distinct values seen so far.
2 Approach
Maintain a tiny sorted list of at most three distinct values; skip duplicates.
3 Complexity Analysis
Time O(n), Space O(1).
4 Solution Code
class Solution:
def thirdMax(self, nums: list[int]) -> int:
top = []
for x in nums:
if x in top:
continue
top.append(x)
top.sort(reverse=True)
if len(top) > 3:
top.pop()
return top[2] if len(top) == 3 else top[0]
5 Code Walkthrough
The reference solution below implements the approach step by step.