Algos and Data Structures problem -3

Question

Find the second highest and the third highest number from int[] numbers = { 2, 3, 4,5,6,7,8}

Answer

Now the given question says that we not need to find the largest or the highest number out of the given array but the second highest and the third highest with O(n).

Actually O(n) not given in the question but we need to solve in an optimal way 

So the solution of it is easy just we need to take some extra variables and need to update it.

Here code goes

int[] numbers = { 2, 3, 4,5,6,7,8}; // you need to get the second and the third highest number of it
        Integer max_num = null;
        Integer secondMax = null;
        Integer thirdMax = null;
        for (Integer num : numbers) {
            if (num.equals(max_num) || num.equals(secondMax) || num.equals(thirdMax)) {
                continue;
            }// this condition is for checking the repetitive numbers must not be processed
            if (max_num == null || num > max_num) {
                thirdMax=secondMax;
                secondMax=max_num;
                max_num=num;
            }//this is case 1
            
            else if (secondMax == null || num > secondMax) {
                thirdMax=secondMax;
                secondMax=num;
            }//case 2 
            
            else if(thirdMax==null||num>thirdMax) {
               thirdMax=num;
            }
            
        }
        
        System.out.println(max_num);
        System.out.println(secondMax);
        System.out.println(thirdMax);
    }

I have added comments in the code itself to understand it better 
You can copy the code and check and can comment if you have any better solution for it 🙂.

Comments

Popular posts from this blog

State space search / blocks world problem by heuristic approach /TIC TAC TOE

Navigation in Vaadin.

Drag and drop items from one Grid to another