Skip to main content
Back to problems
Leetcode
Medium
Arrays
Sorting
Sets
Third Maximum Number

Return the third distinct maximum number in an array, or the maximum number if fewer than three distinct values exist.

Acceptance 0%
Problem Statement

Given an integer array nums, find the third distinct maximum number in the array.

A number is considered distinct if it is different from all previously counted values. If the third distinct maximum does not exist, return the maximum value in the array instead.

The array may contain duplicate values, and duplicates should not affect the distinct ranking.

Input Format

  • An integer array nums.

The array is provided directly as the input collection.

Output Format

  • Return a single integer: the third distinct maximum value if it exists.
  • Otherwise, return the maximum value in the array.

Constraints

  • 1 <= nums.length
  • nums[i] are integers
  • Duplicates may appear
  • Distinct values determine the ranking, not occurrences
Examples
Sample cases returned by the problem API.

Example 1

Input

nums = [3, 2, 1]

Output

1

Explanation

The distinct values in descending order are 3, 2, 1. The third distinct maximum is 1.

Example 2

Input

nums = [1, 2]

Output

2

Explanation

There are fewer than three distinct values, so return the maximum value, which is 2.

Show 1 more example

Example 3

Input

nums = [2, 2, 3, 1]

Output

1

Explanation

The distinct values in descending order are 3, 2, 1. The third distinct maximum is 1.

Premium problem context

Unlock deeper context for this problem

Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.

Guided hints
Editorial and discussion links
Concept map and variants
Sign in to unlock
Track your progress
Sign in to bookmark this problem, save notes, and manage its revision plan.