Elements for which no greater element exist or for the last element (even a greater element may exist in the previous numbers and can be find for the last element, however that is not in scope for this problem), print next greater element as -1
public class NxtgrtElement {
public static void main(String[] args)
{
// TODO Auto-generated method stub
//int a[]={4, 15, 2, 9, 20, 11, 13}; //Array 1
int a[]={4, 20, 2, 9, 15, 11, 13}; // Array 2
printNxtGrtElement(a);
}
/* You are given an array, print the next greater element for each element.
Elements for which no greater element exist, print next greater element as -1.
*/
public static void printNxtGrtElement(int a[])
{
int i=0;
for( i=0; i<a.length-1;i++)
for(int j=i+1; j<a.length;j++)
{
if(a[j]>a[i])
{
System.out.println(a[i] + "->" + a[j]);
break;
}
if(j==a.length-1)
{
for(int k=0; k<i;k++) // This loop will check if it can find the greater number in the already traversed numbers
{
if(a[k]>a[i])
{
System.out.println(a[i] + "->" + a[k]);
break;
}
if(k==i-1)
System.out.println(a[i] + "-> -1" );
}
}
}
System.out.println(a[i] + "-> -1");
}
}
//Complexity- O(n^2)
Output for Array 2-
4->20
20-> -1
2->9
9->15
15->20
11->13
13-> -1
Output for Array 1-
4->15
15->20
2->9
9->20
20-> -1
11->13
13-> -1
No comments:
Post a Comment