Third Maximum Number

Given an integer array `nums`, return the third largest distinct number in it. If there are fewer than three distinct numbers, return the largest number instead.

30:00

Third Maximum Number
easy
Free written solution
Topics
Companies

Given an integer array nums, return the third largest distinct number in it. If there are fewer than three distinct numbers, return the largest number instead.

Example 1:
Input: {"nums":[3,2,1]}
Output: 1
Constraints:
  • 1≤nums.length≤1041 \leq \text{nums.length} \leq 10^4

  • −231≤nums[i]≤231−1-2^{31} \leq \text{nums}[i] \leq 2^{31} - 1

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"nums":[3,2,1]}

nums (scanned left to right)

3
2
1

Podium of distinct maxima

-inf

2

second

-inf

1

first

-inf

3

third

Scan 3 numbers once, keeping only the three largest distinct values seen so far.

Variables
VariableValue
n3
DepthFunction Call
Stack empty
0/8