Introduction

Print all the leaders in an array. An element is a leader if it's greater than all the elements to it's right (the rightmost element is always a leader).

Input:
[16, 17, 4, 3, 5, 2]

Output:
17, 5 and 2
Sample Example

Approach

The approach is to scan from right to left in the array, keeping track of the maximum. We print it after storing it in the output array.

using System;
using System.Linq;
using System.Collections.Generic;
public class GFG {
	static public void Main () {
	    var t = int.Parse(Console.ReadLine());
	    while (t-- > 0) {
	        var n = int.Parse(Console.ReadLine());
	        var arr = Console.ReadLine().Split(" ").Where(a => int.TryParse(a, out _)).Select(a => int.Parse(a)).ToList();
	        var max = arr[arr.Count - 1];
	        var output = new List<int>();
	        for (var i = arr.Count - 1; i > -1; i--) {
	            if (arr[i] >= max) {
	                max = arr[i];
	                output.Add(max);
	            }
	        }
	        output.Reverse();
	        Console.WriteLine(string.Join(" ", output));
	    }
	}
}
Program to scan from right to left and printing the output