From f81fabe653de4416e4b97fbea80f2ecfbf262be5 Mon Sep 17 00:00:00 2001 From: Ipsita Goel <45857758+ipsitagoel@users.noreply.github.com> Date: Fri, 3 Sep 2021 20:20:32 +0530 Subject: [PATCH] chore(CPlusPlus): add leaders in arrays (#444) --- .../CPlusPlus/Arrays/leaders-in-array.cpp | 35 +++++++++++++++++++ algorithms/CPlusPlus/README.md | 1 + 2 files changed, 36 insertions(+) create mode 100644 algorithms/CPlusPlus/Arrays/leaders-in-array.cpp diff --git a/algorithms/CPlusPlus/Arrays/leaders-in-array.cpp b/algorithms/CPlusPlus/Arrays/leaders-in-array.cpp new file mode 100644 index 00000000..a2aba38c --- /dev/null +++ b/algorithms/CPlusPlus/Arrays/leaders-in-array.cpp @@ -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 +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; +} \ No newline at end of file diff --git a/algorithms/CPlusPlus/README.md b/algorithms/CPlusPlus/README.md index 6344f48d..9fae1305 100644 --- a/algorithms/CPlusPlus/README.md +++ b/algorithms/CPlusPlus/README.md @@ -13,6 +13,7 @@ 9. [Fractional Knapsack](Arrays/fractional-knapsack.cpp) 10. [Quick Selection](Arrays/quick-select.cpp) 11. [Remove Duplicates](Arrays/remove-duplicates.cpp) +12. [Leaders In The Array](Arrays/leaders-in-array.cpp) ## Dynamic-Programming