Solving Leetcode Interviews in Seconds with AI: Third Maximum Number
Introduction
In this blog post, we will explore how to solve the LeetCode problem "414" using AI. LeetCode is a popular platform for preparing for coding interviews, and with the help of AI tools like Chatmagic, we can generate solutions quickly and efficiently - helping you pass the interviews and get the job offer without having to study for months.
Problem Statement
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. Example 1: Input: nums = [3,2,1] Output: 1 Explanation: The first distinct maximum is 3. The second distinct maximum is 2. The third distinct maximum is 1. Example 2: Input: nums = [1,2] Output: 2 Explanation: The first distinct maximum is 2. The second distinct maximum is 1. The third distinct maximum does not exist, so the maximum (2) is returned instead. Example 3: Input: nums = [2,2,3,1] Output: 1 Explanation: The first distinct maximum is 3. The second distinct maximum is 2 (both 2's are counted together since they have the same value). The third distinct maximum is 1. Constraints: 1 <= nums.length <= 104 -231 <= nums[i] <= 231 - 1 Follow up: Can you find an O(n) solution?
Explanation
Here's the solution to find the third distinct maximum number in an array efficiently:
- Maintain Three Variables: Use three variables to track the first, second, and third largest distinct numbers encountered so far. Initialize them to negative infinity.
- Iterate and Update: Iterate through the array, and for each number, update the variables based on whether it's larger than the current first, second, or third maximum, ensuring distinctness.
Handle Non-Existence: After iterating, if the third maximum is still negative infinity, it means there weren't three distinct numbers, so return the first maximum instead.
Runtime & Storage Complexity: O(n) runtime, O(1) storage.
Code
def thirdMax(nums):
"""
Finds the third distinct maximum number in an array.
Args:
nums: An array of integers.
Returns:
The third distinct maximum number, or the maximum number if the third
maximum does not exist.
"""
first_max = float('-inf')
second_max = float('-inf')
third_max = float('-inf')
for num in nums:
if num > first_max:
third_max = second_max
second_max = first_max
first_max = num
elif num > second_max and num < first_max:
third_max = second_max
second_max = num
elif num > third_max and num < second_max:
third_max = num
if third_max == float('-inf'):
return first_max
else:
return third_max