Leaders in an array Geeks solution
Problem :
Write a program to print all the LEADERS in the array. An element is leader if it is greater than all the elements to its right side. The rightmost element is always a leader.
Idea is to traverse array from right to left and check if it is greater than its next element and also greater than maximum till the index , if so push it to stack.
code:
import java.util.*;
import java.lang.*;
import java.io.*;
class GFG
{
public static void main (String[] args)
{
Scanner ab=new Scanner(System.in);
int t=ab.nextInt();
while(t-->0)
{
int n=ab.nextInt();
boolean flag=false;
int arr[]=new int[n];
for(int i=0;i<n;i++)
arr[i]=ab.nextInt();
int max=arr[n-1];
Stack<Integer> st=new Stack<Integer>();
for(int i=n-2;i>=0;i--)
{
if(arr[i]>arr[i+1] && arr[i]>max)
{
st.push(arr[i]);
}
max=Math.max(max,arr[i]);
}
if(st.search(arr[n-1])==-1)
flag=true;
while(st.size()>0)
System.out.print(st.pop()+" ");
if(flag)
System.out.print(arr[n-1]);
System.out.println();
}
}
}
0 Comments:
Post a Comment