chore(CPlusPlus): add leaders in arrays (#444)

pull/447/head
Ipsita Goel 2021-09-03 20:20:32 +05:30 committed by GitHub
parent 7ce3167f87
commit f81fabe653
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 36 additions and 0 deletions

View File

@ -0,0 +1,35 @@
// C++ code to print leaders in an array
// Description: If an element is greater than all the elements to its right, the element is a leader
// Method: From right to left in the array, scan all elements and record the maximum element until now. When the maximum element changes, print it
// Time Complexity: O(n)
#include <bits/stdc++.h>
using namespace std;
void findLeader(int a[], int len)
{
int rmax = a[len - 1];
cout << rmax; // The rightmost element is always a leader
cout << endl;
for (int i = len - 2; i >= 0; i--)
{
if (rmax < a[i])
{
rmax = a[i];
cout << rmax;
cout << endl;
}
}
}
int main()
{
int n;
cin >> n; // Take the size of the array as input from the user
int a[n];
for (int i = 0; i < n; i++)
{
cin >> a[i]; // Take the elements of the array as input from the user
}
findLeader(a, n);
return 0;
}

View File

@ -13,6 +13,7 @@
9. [Fractional Knapsack](Arrays/fractional-knapsack.cpp) 9. [Fractional Knapsack](Arrays/fractional-knapsack.cpp)
10. [Quick Selection](Arrays/quick-select.cpp) 10. [Quick Selection](Arrays/quick-select.cpp)
11. [Remove Duplicates](Arrays/remove-duplicates.cpp) 11. [Remove Duplicates](Arrays/remove-duplicates.cpp)
12. [Leaders In The Array](Arrays/leaders-in-array.cpp)
## Dynamic-Programming ## Dynamic-Programming