Show problems as
Classic problem #414EasyArraySorting

Third Maximum Number

Real-world version: Third Highest Distinct Reading
Tracked in this browser only
Read Third Maximum Number on LeetCode(opens in a new tab)

The statement here is our own: the same inputs, outputs and technique.

A weather post logs one temperature change per day of a survey into the list readings. A change may be positive, zero or negative, and the same change can be logged on several days.

Collapse repeats so that each value present in readings is considered once, then rank those values from largest down. Return the value in third place. When the survey holds fewer than three different values, return the largest value instead.

Examples

Example 1

Input
readings = [4, 9, -6, 4, 12]
Output
4

The different values logged are 12, 9, 4 and -6. Ranking them from largest down gives 12 first, 9 second and 4 third, so 4 is returned.

Example 2

Input
readings = [7, 7, 7]
Output
7

Every day logged the same change, so the survey holds one different value. That is fewer than three, so the largest value 7 is returned.

Example 3

Input
readings = [2147483647, 0, -2147483648]
Output
-2147483648

All three values differ. Ranked from largest down they are 2147483647, 0 and -2147483648, so third place holds -2147483648.

Constraints

  • 1 <= readings.length <= 10^4
  • -2^31 <= readings[i] <= 2^31 - 1

The signature

The editor starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.

Python
def third_max(readings: list[int]) -> int:
Java
public int thirdMax(int[] readings)