Third largest element in an array of distinct elements

 

Given an array of n integers, the task is to find the third largest element. All the elements in the array are distinct integers. 

Examples : 

Input: arr[] = {1, 14, 2, 16, 10, 20}
Output: 14
Explanation: Largest element is 20, second largest element is 16 and third largest element is 14

Input: arr[] = {19, -10, 20, 14, 2, 16, 10}
Output: 16
Explanation: Largest element is 20, second largest element is 19 and third largest element is 16

 

 

class ThirdLargest{
    public int thirdLargest(int[] arr){

        int  n = arr.length();

        int f = Integer.MIN_VALUE; 

        int s = Integer.MIN_VALUE;

        int t = Integer.MIN_VALUE;

     for(int i = 0 ; i< n ; i++){

        if(arr[i] > f){

            t = s;

            s = f;

            f = arr[i]; 

        }else if(arr[i] > s){

            t = s;

            s = arr[i];

        }else{

                t = arr[i]; 

         }

    }

    return t;

    }

}

 

Comments

Popular Posts