CoCubes Programming Question – 1
Printing all the Leaders in an Array
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, 19, 4, 3, 8, 3}, leaders are 19, 8 and 3?
C++
Java
C++
#include<iostream> using namespace std; void findLeaders(int arr[], int size) { for (int i = 0; i < size; i++) { int j; for (j = i+1; j < size; j++) { if (arr[i] <= arr[j]) break; } if (j == size) cout << arr[i] << " "; } } int main() { int len, i; cout<< "Enter the length of the array\n"; cin >> len; int arr[len]; cout<< "Enter the elements of the array\n"; for( i=0; i<len; i++) { cin>>arr[i]; } int n = sizeof(arr)/sizeof(arr[0]); findLeaders(arr, n); return 0; }
Java
class LeadersInArray { /*Java Function to print leaders in an array */ void printLeaders (int arr[], int size) { for (int i = 0; i < size; i++) { int j; for (j = i + 1; j < size; j++) { if (arr[i] <= arr[j]) break; } if (j == size) System.out.print(arr[i] + " "); } } /* Driver program to test above functions */ public static void main (String[]args) { LeadersInArray lead = new LeadersInArray (); int arr[] = new int[]{ 16, 17, 4, 3, 5, 2 }; int n = arr.length; lead.printLeaders (arr, n); } }
#include
using namespace std;
void findLeaders(int arr[],int len){
int leaders[]={};
for(int i=0;i<len;i++){
int flag=0;
// cout<<"\n a[i]: "<<arr[i];
for(int j=i+1;j<len;j++){
//cout<<"\t \t a[j]: "<<arr[j];
if(arr[i]<arr[j]){
flag=1;
break;
}
}
if(flag==0)
cout<<" | "<<arr[i];
}
}
int main() {
// // Write C++ code here
// int arr[]={16, 19, 4, 3, 8, 3};
// //leaders: 19, 8 and 3?
// int len=sizeof(arr)/sizeof(arr[0]);
// cout<<"\nlength: "<<len;
// findLeaders(arr,len);
int len;
cout<>len;
int arr[len];
cout<<"\n Enter Array Elements: ";
for(int i=0;i>arr[i];
cout<<"\n Leader Array: ";
findLeaders(arr,len);
return 0;
}
Time comp: O(n)
Python 3
ip = list(map(int,input().split()))
leaders = []
max = ip[-1]
for i in ip[::-1]:
If i > max:
leaders.insert(0,i)
max = i
leaders.append(ip[-1])
print(leaders)
import java.util.*;
public class Main
{
public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
LinkedHashSet l =new LinkedHashSet();
int n =s.nextInt();
int ar[] = new int[n];
for(int i =0;i0;i–)
{
if(ar[i]>max)
{
l.add(ar[i]);
max=ar[i];
}
}
System.out.println(l);
}
}