Java: Print all the LEADERS in the array
Write a Java program to print all the LEADERS in the array.
Note: An element is leader if it is greater than all the elements to its right side.
Pictorial Presentation:
Sample Solution:
Java Code:
// Import necessary Java libraries.
import java.util.HashMap;
import java.util.Map;
import java.util.Iterator;
import java.util.Arrays;
// Define a class named Main.
public class Main
{
// The main method for executing the program.
public static void main(String[] args)
{
// Define an array of integers.
int arr[] = {10, 9, 14, 23, 15, 0, 9};
int size = arr.length;
// Loop through each element in the array.
for (int i = 0; i < size; i++)
{
int j;
// Find the first element greater than or equal to arr[i].
for (j = i + 1; j < size; j++)
{
if (arr[i] <= arr[j])
break;
}
// If no greater element is found, print the current element.
if (j == size)
System.out.print(arr[i] + " ");
}
}
}
Sample Output:
23 15 9
Flowchart:
Java Code Editor:
Previous: Write a Java program to get the majority element from a given array of integers containing duplicates.
Next: Write a Java program to find the two elements from a given array of positive and negative numbers such that their sum is closest to zero.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics