DEV Community

Cover image for Solving LeetCode 414 Third Maximum Number: A Streamlined Java Approach
Jerin
Jerin

Posted on

Solving LeetCode 414 Third Maximum Number: A Streamlined Java Approach

Difficulty: Easy

Topics: Array, Sorting

Platform: Leetcode

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.

Problem Statement Simplified

Give back the 3rd largest number from the array if it exists, else give back the largest number.

Mistakes and Learning

Confusing over the array indexing and length—array indexing starts at 0 and length starts at 1, always forget that.

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.
Enter fullscreen mode Exit fullscreen mode

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.
Enter fullscreen mode Exit fullscreen mode

Key Insight

  1. Sort the array.
  2. Get the unique array.
  3. If less than 3, then return the largest.
  4. Else return the nums.length - 3.

Algorithm

  1. Sort the array.
  2. Initialize an array to store the unique array, using stream , distinct operation and toArray to make it into an array.
  3. If the array length is less than 3 then return the last digit of the array.
  4. Else return the element in total length-3.
  5. End if.

Algorithm in simple words

Fisrt sort the array in ascending order to get the elements in order. Then find out the duplicating element using distinct() operation and discard it.
Then using an if statment check if the array length is less than 3 , if yes then return the last digit which will be the largest digit.

If greater than 3 then return the element in total length-3 that will be the 3rd largest digit.

Java code

class Solution {
    public int thirdMax(int[] nums) {
        Arrays.sort(nums);
        int[] uniqueArr= Arrays.stream(nums).distinct().toArray();
        if(uniqueArr.length<3){
            return uniqueArr[uniqueArr.length-1];
        }
        else{
            return uniqueArr[uniqueArr.length-3];
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Time & Space Complexity

Time Complexity: O(nlogn)

Space Complexity: O(n)

Top comments (0)