Summary: This C program identifies leader elements in an array. A leader is an element that is greater than all the elements to its right. The last element is always a leader by definition.
#include <stdio.h>
void findLeaders(int arr[], int n) {
int leaders[n]; // Array to store leaders
int count = 0; // To keep track of the number of leaders
int maxFromRight = arr[n - 1]; // Last element is always a leader
// Store the rightmost leader
leaders[count++] = maxFromRight;
// Traverse the array from second last to the first element
for (int i = n - 2; i >= 0; i--) {
if (arr[i] > maxFromRight) {
maxFromRight = arr[i]; // Update maxFromRight
leaders[count++] = maxFromRight;
}
}
// Print leaders in correct order (reverse of the array)
printf("Leaders: ");
for (int i = count - 1; i >= 0; i--) {
printf("%d ", leaders[i]);
}
printf("\n");
}
int main() {
int n;
// Get the number of elements in the array
printf("Enter the number of elements: ");
scanf("%d", &n);
// Check constraints
if (n < 1 || n > 100) {
printf("Invalid number of elements! Please enter a value between 1 and 100.\n");
return 1;
}
int arr[n];
// Get the elements of the array
printf("Enter the elements: ");
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
// Find and print leaders
findLeaders(arr, n);
return 0;
}
Program Overview:
This program identifies leader elements in an array and prints them. A leader is an element that is greater than all elements to its right. The logic involves traversing the array from right to left and comparing each element with the maximum element encountered so far.
findLeaders()
:The function findLeaders()
takes two parameters:
arr[]
: The array of integers.n
: The size of the array.It identifies the leader elements and prints them in the correct order.
leaders
array.maxFromRight
keeps track of the maximum element encountered while traversing the array from right to left.maxFromRight
.maxFromRight
, it is considered a leader.leaders
array and maxFromRight
is updated to this element.arr[]
.findLeaders()
to Identify and Print Leaders:
findLeaders()
function is called with the array and its size.O(n)
, since the array is traversed once from right to left.O(n)
for any input size.O(n)
as the leader elements are stored in an additional array.