โ† Back to Index

๐Ÿ“š Third Maximum Number โ€“ Java Cheat Sheet

๐Ÿ“Œ What Is It?

The Third Maximum Number problem involves finding the third distinct maximum number in an array. If the third maximum does not exist, return the maximum number.

This problem can be solved using a set or a min-heap to track distinct maximum numbers.

๐Ÿงฑ Pattern Template

class Solution {
    public int thirdMax(int[] nums) {
        PriorityQueue<Integer> minHeap = new PriorityQueue<>();
        Set<Integer> seen = new HashSet<>();

        for (int num : nums) {
            if (!seen.contains(num)) {
                seen.add(num);
                minHeap.offer(num);
                if (minHeap.size() > 3) {
                    minHeap.poll(); // Remove the smallest element
                }
            }
        }

        // If there are less than 3 distinct numbers, return the maximum
        if (minHeap.size() < 3) {
            while (minHeap.size() > 1) {
                minHeap.poll();
            }
        }

        return minHeap.peek();
    }
}

๐Ÿ“Š Time Complexity

โœ… Use Cases

๐Ÿ“˜ Common LeetCode Problems

๐Ÿงช Example: Third Maximum Number

Input: nums = [3, 2, 1]
Output: 1

Explanation:
- The distinct maximum numbers are [3, 2, 1].
- The third maximum number is 1.

๐Ÿ’ก Pro Tips