Leaders in Java
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. And the rightmost element is always a leader. For example int the array {16, 17, 4, 3, 5, 2}, leaders are 17, 5 and 2.
Sample Test Case:
Sample Input:-
6
16 17 4 3 5 2
Sample Output -
17
5
2
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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. And the rightmost element | |
* is always a leader. For example int the array | |
* {16, 17, 4, 3, 5, 2}, leaders are 17, 5 and 2. | |
* | |
* Input Format - You will take an integer as input from | |
* STDIN which represent the length of the array and on | |
* another line array elements will be there separated by | |
* single space. | |
Output Format - print the numbers one on each line to the STDOUT. | |
Sample Test Case: | |
Sample Input:- | |
6 | |
16 17 4 3 5 2 | |
Sample Output - | |
17 | |
5 | |
2 | |
*/ | |
import java.util.*; | |
public class Leader { | |
public static void main(String [] args){ | |
Scanner sc=new Scanner(System.in); | |
int size; | |
size=sc.nextInt(); | |
int [] arr=new int [size]; | |
for(int i=0;i<size;i++){ | |
arr[i]=sc.nextInt(); | |
} | |
int value=0; | |
for(int a=0;a<arr.length;a++){ | |
for(int b=a+1;b<arr.length;b++){ | |
if(arr[a]>arr[b]){ | |
value=arr[a]; | |
}else{ | |
value=0; | |
break; | |
} | |
} | |
if(value>0) | |
System.out.println(arr[a]); | |
} | |
sc.close(); | |
} | |
} |
Sample Test Case:
Sample Input:-
6
16 17 4 3 5 2
Sample Output -
17
5
2
Comments
Post a Comment