DevPath

← All problems

Third Maximum Number

Easy arrays · sorting

Description

Return the third distinct maximum value, or the maximum if fewer than three distinct values exist.

Constraints

1 <= n <= 100000

Examples

Input: nums = [3,2,1]

Output: 1

Hints (1)
  • Deduplicate and take the third element after sorting descending.

Solutions

Dedup and sort. (requires "sort") · Time O(n log n) · Space O(n)

func thirdMax(nums []int) int {
    seen := map[int]bool{}
    u := []int{}
    for _, n := range nums {
        if !seen[n] {
            seen[n] = true
            u = append(u, n)
        }
    }
    sort.Sort(sort.Reverse(sort.IntSlice(u)))
    if len(u) >= 3 {
        return u[2]
    }
    return u[0]
}

Create a free account to submit solutions, track progress and save problems.

Create account