The problem of finding the third maximum number is a popular coding interview question. Here you will be given an array, and you have to return the third largest number in the array as an output. So, if you want to learn how to find the third maximum number in the array, this article is for you. This article will take you through how to find the third maximum number using Python.
Third Maximum Number
In the problem of finding the third maximum number in an array, you will be given an array of integers. To solve this problem, you need to find the third largest number in the array as an output. For example, look at the input and output of this problem shown below:
- Input: [3, 2, 1] | Output: 1
- Input: [2, 2, 3, 1] | Output: 1
Third Maximum Number using Python
I hope you have now understood what the problem of finding the third maximum number means. Below is how you can solve this problem using the Python programming language:
def thirdMax(nums): nums.sort(reverse = True) count = 1 previous = nums[0] for i in range(len(nums)): if nums[i] != previous: count = count + 1 previous = nums[i] if count == 3: return nums[i] return nums[0] nums = [10, 2, 4, 5, 6, 2, 9, 1, 7, 5, 4, 11, 30] print(thirdMax(nums))
Output: 10
So this is how you can find the third maximum number using Python. You can find many more practice questions for coding interviews solved and explained using Python here.
Summary
In the problem of finding the third maximum number in an array, you will be given an array of integers. To solve this problem, you need to find the third largest number in the array as an output. I hope you liked this article on finding the third maximum number in the array using Python. Feel free to ask valuable questions in the comments section below.