Skip to main content

Third Maximum Number LeetCode solution in Java | Programming Blog

How to find Third Maximum Number in given Java array?

Find 3rd maximum number using Arrays.sort(), TreeSet and PriorityQueue in java

Problem Description :

Given integer array nums, return the third 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 third maximum is 1.

Example 2 :

Input: nums = [1,2]
Output: 2
Explanation: The third maximum does not exist, 
so the maximum (2) is returned instead.

Example 3 :

Input: nums = [2,2,3,1]
Output: 1
Explanation: Note that the third maximum here means 
the third maximum distinct number. Both numbers with value 2 are both considered as second maximum.

In this problem, we have to find 3rd maximum number in given array. If 3rd maximum is not present in array then we have to return maximum number that is present in array. So lets jump on solution and explanation.

Solution 1 : Using Arrays.sort()

class Solution {
    public int thirdMax(int[] nums) {

        // Sort array
        Arrays.sort(nums);
       
        int thirdMaxNumber = nums[nums.length-1];
        int temp = 1;
        
        // Traverse array from right to left (Max number to min number)
        for (int i = nums.length-1; i > 0 ; i--) {
           
            if (temp == 3) {
                break;
            }
           
            // Check array values are not same
            if (nums[i-1] != thirdMaxNumber) {
                thirdMaxNumber = nums[i-1];
                ++temp;
            }
        }
       
        // check 3rd max number is present or not
        if (temp < 3) {
            thirdMaxNumber = nums[nums.length-1];
        }
        
        return thirdMaxNumber;
    }
}

Solution explanation :

  • Sort the given nums array using Arrays.sort() method.
  • Declare and assign two int variable : assign last array value to thirdMaxNumber and 1 to temp variable.
  • After sort, traverse array from right to left (max number to min number).
  • Check if temp variable value is 3 or not. if it is 3 then we break the for loop (After got 3rd max number).
  • In second if condition, check if nums[i-1] value are not same as thirdMaxNumber. (because we need third maximum distinct number). If not same then assign nums[i-1] value to thirdMaxNumber and increment temp by one.
  • After completion of for loop, check if temp is less than 3. if it is less than 3 that means given array does not contains 3rd max number. so we have to return max number.

Output explanation :

nums = [2, 2, 3, 1]

After Arrays.sort() array becomes :
nums = [1, 2, 2, 3]

  • thirdMaxNumber = 3, temp = 1
  • i = nums.length-1 | i = 3
    • First If.
    • temp == 3 | 1 == 3 becomes false.
    • Second If
    • nums[2] != 3 | 2 != 3 becomes true.
      • thirdMaxNumber = nums[2] | thirdMaxNumber = 2
      • temp++ | temp = 2

  • i = 2,  thirdMaxNumber = 2, temp = 2
    • 2 == 3 becomes false.
    • 1 != 3 becomes true.
      • thirdMaxNumber = 1
      • temp =3

  • i = 3,  thirdMaxNumber = 1, temp = 3
    • 3 == 3 becomes true and break the for loop.

  • temp < 3 | 3 < 3 becomes false.
  • return  thirdMaxNumber that is 1.

 

Lets see another solution using Priority Queue.

Learn more about Priority Queue :

Solution 2 : Get 3rd Maximum number using Priority Queue in Java

import java.util.PriorityQueue; 
class Solution {
    public int thirdMax(int[] nums) {

        // Get minimum value of integer
int maxNumber = Integer.MIN_VALUE;

PriorityQueue<Integer> pq = new PriorityQueue<Integer>();

for(int i : nums){

    // Get maximum number
    maxNumber = Math.max(maxNumber, i);

    // Add number in priority queue if not exists
    if(!pq.contains(i)) {
pq.add(i);
     }

    // Remove 3rd largest afterward number
    if(pq.size() > 3) {
pq.poll();
    }
}

// Return 3rd max number if queue size greter than 3
// otherwise return Maximum number of given array
return pq.size() == 3 ? pq.peek() : maxNumber;

    }
}

Solution explanation :

  • Declare an integer number and assign minimum value of integer using Integer.MIN_VALUE.
  • Create new  PriorityQueue.
  • Traverse through given nums array using for each loop.
  • Get maximum number from current array index or maxNumber variable.
  • If PriorityQueue does not contains array value then add using add() method.
  • Remove from PriorityQueue using poll() method, when size becomes greater than 3. 
  • Return 3rd max number if present otherwise return maximum number of given array.

Output explanation :

nums = [2, 2, 3, 1, 5, 1, 6]

  • i = 0, pq = []
    • pq does not contains 2. add 2 in pq | pq = [2]
    • pq.size() > 3 becomes false.

  • i = 1, pq = [2]
    • pq contains 2.
    • pq.size() > 3 becomes false.

  • i = 2, pq = [2]
    • pq does not contains 3. add 3 in pq | pq = [2, 3]
    • pq.size() > 3 becomes false.

  • i = 3, pq = [2, 3]
    • pq does not contains 1. add 1 in pq | pq = [1, 3, 2]
    • pq.size() > 3 becomes false.

  • i =  4, pq = [1, 3, 2]
    • pq does not contains 5. add 5 in pq | pq = [1, 3, 2, 5]
    • pq.size() > 3 becomes true | Remove from pq | pq = [2, 3, 5]

  • i = 5, pq = [2, 3, 5]
    • pq does not contains 1 | add 1 in pq | pq = [1, 2, 5, 3]
    • pq.size() > 3 becomes true | Remove from pq | pq = [2, 3, 5]

  • i = 6, pq = [2, 3, 5]
    • pq does not contains 6 | add 6 in pq | pq = [2, 3, 5, 6]
    • pq.size() > 3 becomes true | Remove from pq | pq = [3, 6, 5]

  • For loop ends
  • pg.peek() | return 3 

Lets discuss third solution using TreeSet.

Solution 3 : Get 3rd Maximum number using TreeSet in Java

import java.util.TreeSet; 
class Solution {
    public int thirdMax(int[] nums) {

        TreeSet<Integer> ts = new TreeSet<Integer>();
for(int n: nums) {

    ts.add(n);

            // Remove first element if treeset size becomes
            // greater than 3
if(ts.size() > 3) {
    ts.pollFirst();
}
}

return ts.size() < 3 ? ts.pollLast() : ts.pollFirst();

    }
}

Key point of TreeSet in Java :

  • TreeSet data structure stores unique elements and sorts the elements in ascending order.

Solution explanation :

  • Create new TreeSet.
  • Traverse through given nums array and store elements one by one. TreeSet stores only unique value so we need not to check if element is already exist or not.
  • If TreeSet size becomes greater than 3 then removes first element.
  • Return 3rd ma element if TreeSet size is greater than 0, otherwise return max element of given array.

 

Happy Coding.

Other problem and solution in Java :

Comments

Popular posts from this blog

Plus Minus HackerRank Solution in Java | Programming Blog

Java Solution for HackerRank Plus Minus Problem Given an array of integers, calculate the ratios of its elements that are positive , negative , and zero . Print the decimal value of each fraction on a new line with 6 places after the decimal. Example 1 : array = [1, 1, 0, -1, -1] There are N = 5 elements, two positive, two negative and one zero. Their ratios are 2/5 = 0.400000, 2/5 = 0.400000 and 1/5 = 0.200000. Results are printed as:  0.400000 0.400000 0.200000 proportion of positive values proportion of negative values proportion of zeros Example 2 : array = [-4, 3, -9, 0, 4, 1]  There are 3 positive numbers, 2 negative numbers, and 1 zero in array. Following is answer : 3/6 = 0.500000 2/6 = 0.333333 1/6 = 0.166667 Lets see solution Solution 1 import java.io.*; import java.math.*; import java.security.*; import java.text.*; import java.util.*; import java.util.concurrent.*; import java.util.function.*; import java.util.regex.*; import java.util.stream.*; import static java.util.st

Flipping the Matrix HackerRank Solution in Java with Explanation

Java Solution for Flipping the Matrix | Find Highest Sum of Upper-Left Quadrant of Matrix Problem Description : Sean invented a game involving a 2n * 2n matrix where each cell of the matrix contains an integer. He can reverse any of its rows or columns any number of times. The goal of the game is to maximize the sum of the elements in the n *n submatrix located in the upper-left quadrant of the matrix. Given the initial configurations for q matrices, help Sean reverse the rows and columns of each matrix in the best possible way so that the sum of the elements in the matrix's upper-left quadrant is maximal.  Input : matrix = [[1, 2], [3, 4]] Output : 4 Input : matrix = [[112, 42, 83, 119], [56, 125, 56, 49], [15, 78, 101, 43], [62, 98, 114, 108]] Output : 119 + 114 + 56 + 125 = 414 Full Problem Description : Flipping the Matrix Problem Description   Here we can find solution using following pattern, So simply we have to find Max of same number of box like (1,1,1,1). And last