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]
```

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;
}
```

Hope this algorithm works. Thank you ❤.

## Top comments (0)