Reading:
Third maximum number in an array

Third maximum number in an array

Metamug

//: # ()

Finding the third maximum number in an array is a popular leetcode #414 question.It is commonly asked in interviews with the follow up question to use time complexity as O(n) and space complexity as O(1).

Start with lowest value possible. Here instead of using Integer.MIN_VALUE we have used Long.MIN_VALUE, which helps us pass cases where lowest integer value is given in the array.

class Solution {

    public int thirdMax(int[] nums) {

        long max, smax, tmax;

        max = smax = tmax = Long.MIN_VALUE;

        for(int n: nums){

            if(n == max || n == smax || n == tmax)
                continue;

            if(n >= max ){
                tmax = smax;
                smax = max;
                max = n;
            }else if(n > smax){
                tmax = smax;
                smax = n;
            }else if(n >= tmax){
                tmax  = n;

            }
        }

        if( tmax == Long.MIN_VALUE ) {
            tmax = max;
        }

        return (int)tmax;

    }
}

In the end, if third max value is not present, make max as third max and return.



Icon For Arrow-up
Comments

Post a comment