DEV Community

Sadiul Hakim
Sadiul Hakim

Posted on

Algorithm part-1 : Next Greater Element Algorithm

Today i am going to start a new series about algorithms and problem solving. I'll be posting about various problems with their solution. I am going to use java as programming language.

Today i am going to show you How to solve next greater element problem in java.

Let's discuss this problem. In this problem we are given an integer array. We have to find exactly next greater element of each array element. If there is no greater element we will sit -1 at that position.

Example

We are given : [4,5,1,7,3,6,9]
Answer       : [5,7,7,9,6,9,-1]
Enter fullscreen mode Exit fullscreen mode

Let's see the solution...

public int[] nextGreater(int[] arr){
        int[] result=new int[arr.length];

        for(int i=0;i<arr.length;i++){
            int j=i+1;
            int value=arr[i];
            boolean got=false;
            while(j<=arr.length-1){
                if(arr[j] > value){
                    got=true;
                    result[i]=arr[j];
                    break;
                }                
                j++;

            }
            if(!got){
                result[i]=-1;
            }
        }


        return result;
    }
Enter fullscreen mode Exit fullscreen mode

Hope this algorithm works. Thank you ❤.

Top comments (0)