Program to Find Leader Elements in an Array (C)
C
Medium
4 views
Problem Description
Finding leader elements in an array (those greater than the subelements on their right side) - what is the logic behind scanning from right to left?
Official Solution
#include <stdio.h>
int main() {
int arr[100], n, i;
int maxRight;
printf("Enter number of elements: ");
scanf("%d", &n);
printf("Enter array elements:n");
for (i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
printf("Leader elements are:n");
// Rightmost element is always a leader
maxRight = arr[n - 1];
printf("%d ", maxRight);
// Scan from right to left
for (i = n - 2; i >= 0; i--) {
if (arr[i] > maxRight) {
printf("%d ", arr[i]);
maxRight = arr[i];
}
}
return 0;
}
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!