Find Leaders of any array
[Arrays]
#collapse-hide
from typing import List
class Solution:
def findLeaders(self, nums: List[int]) -> int:
result = []
for i in range(len(nums)):
flag = 0
for j in range(i+1, len(nums)):
if nums[i] < nums[j]:
# print(nums[i], " < ", nums[j])
flag = 1
if flag == 1:
break
if flag == 0:
# print(nums[i])
result.append(nums[i])
return result
sol = Solution()
sol.findLeaders([1, 2, 3, 4])
sol.findLeaders([8, 4, 2, 3, 1, 5, 4, 2])
sol.findLeaders([10, 6, 3, 1, 7, 9])
Worst case performance in Time: $O(n^2)$
Image source GeekForGeeks
#collapse-hide
class Solution:
def findLeaders(self, nums: List[int]) -> int:
j = nums[len(nums)-1]
result = []
for i in range(len(nums)-1, -1, -1):
if nums[i] >= j:
j = nums[i]
result.append(j)
return result[::-1]
sol = Solution()
sol.findLeaders([1, 2, 3, 4])
sol.findLeaders([8, 4, 2, 3, 1, 5, 4, 2])
sol.findLeaders([10, 6, 3, 1, 7, 9])
#collapse-hide
import sys
def findLeaders(arr,n):
max_value=-sys.maxsize -1
for i in range(n-1,-1,-1):
if(max_value<arr[i]):
max_value=arr[i]
print(max_value)
findLeaders([16, 17, 4, 3, 5, 2],6)
Worst case performance in Time: $O(n)$