Problem: Given integer array, return the third maximum number in this array. If the third maximum does not exist, return the maximum number.
Example:
Input: nums = [10,11,12] Output: 10 Explanation: The third maximum is 10.
Input: nums = [1,2,2] Output: 2 Explanation: The third maximum here means the third maximum distinct number. Both numbers with value 1 are both considered as second maximum. So third maximum number does not exist, that's why the maximum (2) is returned instead.
Approach: This is a straight forward problem to solve except handling of boundary conditions like minimum value of integer etc. We can handle this kind of conditions using long.
You can understand the approach by just looking at the implementation.
Implementation in C#:
public int ThirdMax(int[] nums)
{
long firstMax = GetMax(nums, long.MaxValue);
long secondMax = GetMax(nums, firstMax);
long thirdMax = GetMax(nums, secondMax);
return thirdMax == long.MinValue ? (int)firstMax : (int)thirdMax;
}
private long GetMax(int[] nums, long upperBound)
{
long max = long.MinValue;
foreach (int num in nums)
{
if (max < num && num < upperBound)
{
max = num;
}
}
return max;
}
Complexity: O(n)
No comments:
Post a Comment