Problem Description
Given an integer array nums, return the third distinct maximum number in this array. If the third maximum does not exist, return the maximum number.
Key Insights
- We need to consider only distinct values in the array.
- Use variables or a data structure to track the top 3 distinct maximum numbers.
- We need an O(n) solution, so we should avoid unnecessary sorting.
- Edge-case: If there are fewer than 3 distinct numbers, the maximum among them should be returned.
Space and Time Complexity
Time Complexity: O(n) because we iterate through the array once.
Space Complexity: O(1) since we only maintain a fixed number of variables.
Solution
We iterate through the nums array and maintain three variables to store the first, second, and third distinct maximum numbers. For each number in the array, we check whether it is already one of the three maximums (to handle duplicates). If not, we update the maximums accordingly:
- If the current number is greater than the first maximum, then update the first, second, and third maximums.
- Else if the current number is between the first maximum and the second, update the second and third maximums accordingly.
- Else if the current number is between the second maximum and the third, update the third maximum.
After processing all elements, if the third maximum is still unassigned (i.e., there are less than three distinct numbers), return the first maximum. This approach uses constant extra space and only one pass through the input array.