Created
July 21, 2020 14:44
-
-
Save Irene-123/43503ca558e07dbd404877fc9802301b to your computer and use it in GitHub Desktop.
Leaders In an Array Python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
''' | |
Problem: You are given an array. You have to write a program that will 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 array {6, 7, 4, 3, 5, 2}, leaders are 7, 5 and 2. | |
''' | |
def Leaders(nums,n): | |
res=[] | |
max_ele=nums[-1] | |
res.append(max_ele) | |
for i in range (n-2,-1,-1): | |
if nums[i]>max_ele: | |
res.append(nums[i]) | |
max_ele=nums[i] | |
return res | |
if __name__=="__main__": | |
n=int(input()) | |
nums=list(map(int,input().strip().split()))[:n] | |
print(Leaders(nums,n)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment