Find your Leader

QUESTION

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, 17, 4, 3, 5, 2}, leaders are 17, 5 and 2.\n\nInput:\nThe first line contains size of the array\nThe second line contains the elements of the array.\n\nOutput:\nPrint leaders present in array\n\nMethod 1 (Simple)\nUse two loops. The outer loop runs from 0 to size 1 and one by one picks all elements from left to right. The inner loop compares the picked element to all the elements to its right side. If the picked element is greater than all the elements to its right side, then the picked element is the leader.

“TESTCASE_1”: “6\n16 17 4 3 5 2\n###—###SEPERATOR—###—\n17\n5\n2”, “TESTCASE_2”: “6\n1 2 3 4 9 4\n###—###SEPERATOR—###—\n9\n4”, “TESTCASE_3”: “5\n1 8 4 3 2\n###—###SEPERATOR—###—\n8\n4\n3\n2”, “TESTCASE_4”: “0\n###—###SEPERATOR—###—\n0”, “TESTCASE_5”: “0\n###—###SEPERATOR—###—\n0

ANSWER

#include <iostream>
using namespace std;
 
/*C++ 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) // the loop didn't break
            cout << arr[i] << "\n";
  	}
  	//printf("\n");
}
 
/* Driver program to test above function */
int main()
{
    int a1[10], a2[10];
    int n1, n2, i, j;
  	//cin>>n;
  	cin>>n1;
  	for(i=0;i<n1;i++)
    {
      cin>>a1[i];
    }
  	cin>>n2;
  	for(j=0;j<n2;j++)
    {
      cin>>a2[j];
 	}
    printLeaders(a1, n1);
  	printLeaders(a2, n2);
    return 0;
}

Ads Blocker Image Powered by Code Help Pro

Ads Blocker Detected!!!

We have detected that you are using extensions to block ads. Please support us by disabling these ads blocker.