Third Maximum Number

Return the third distinct maximum (or the maximum if fewer than 3 distinct exist) — three running tracker variables.

Easy
Time O(n) Space O(1)
LeetCode
4 min read
top-k

Problem#

Return the third distinct maximum number in the array. If fewer than three distinct values exist, return the maximum.

Examples#

  • [3,2,1]1
  • [1,2]2
  • [2,2,3,1]1

Constraints#

  • 1 <= nums.length <= 10^4.

Approach#

Three long long slots m1 > m2 > m3 initialized to a sentinel “unset”. Walk; for each x, slot it into the right rank, demoting others, skipping duplicates.

Solution#

Third Maximum Number
class Solution {
public:
int thirdMax(vector<int>& nums) {
long long m1 = LLONG_MIN, m2 = LLONG_MIN, m3 = LLONG_MIN;
for (int x : nums) {
if (x == m1 || x == m2 || x == m3) continue;
if (x > m1) { m3 = m2; m2 = m1; m1 = x; }
else if (x > m2) { m3 = m2; m2 = x; }
else if (x > m3) { m3 = x; }
}
return m3 == LLONG_MIN ? (int)m1 : (int)m3;
}
};

Editorial#

Three running slots beat heap-based solutions for fixed k=3. The dedup check is x == m1 || m2 || m3, since duplicates would otherwise corrupt the slot demotion. LLONG_MIN is a sentinel because INT_MIN is a valid input value.

Complexity#

  • Time: O(n).
  • Space: O(1).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.