LeetCode 414: Third Maximum Number Solution

Master LeetCode problem 414 (Third Maximum Number), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

414. Third Maximum Number

Problem Explanation

Explanation

To find the third maximum number in an array, we can iterate through the array and keep track of the first, second, and third maximum values. We initialize these variables with negative infinity to handle cases where the maximum values are negative. We update these values accordingly, ensuring that they are distinct. Finally, we return the third maximum if it exists, or the maximum value otherwise.

  • Time Complexity: O(n) where n is the number of elements in the array.
  • Space Complexity: O(1)

Solution Code

class Solution {
    public int thirdMax(int[] nums) {
        long firstMax = Long.MIN_VALUE, secondMax = Long.MIN_VALUE, thirdMax = Long.MIN_VALUE;
        
        for (int num : nums) {
            if (num > firstMax) {
                thirdMax = secondMax;
                secondMax = firstMax;
                firstMax = num;
            } else if (num < firstMax && num > secondMax) {
                thirdMax = secondMax;
                secondMax = num;
            } else if (num < secondMax && num > thirdMax) {
                thirdMax = num;
            }
        }
        
        return (thirdMax == Long.MIN_VALUE || thirdMax == secondMax) ? (int) firstMax : (int) thirdMax;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 414 (Third Maximum Number)?

This page provides optimized solutions for LeetCode problem 414 (Third Maximum Number) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 414 (Third Maximum Number)?

The time complexity for LeetCode 414 (Third Maximum Number) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 414 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 414 in Java, C++, or Python.

Back to LeetCode Solutions