Skip to content

Instantly share code, notes, and snippets.

@ssshukla26
Last active September 15, 2021 20:57
Show Gist options
  • Save ssshukla26/33a7e36dff7c2253413fa9043e953f3e to your computer and use it in GitHub Desktop.
Save ssshukla26/33a7e36dff7c2253413fa9043e953f3e to your computer and use it in GitHub Desktop.
Get Max to the left of an array, this can also be used to get max to the right of an array
nums = [0,1,0,2,1,0,1,3,2,1,2,1]
n = len(nums)
# Function to get max to the left
# of each index of an array
def maxToLeft(arr):
# Nothing left for first index
maxLeft = [-1]
# Find max to the left of each
# index
l = arr[0]
for a in arr[1:]:
l = max(l, a)
maxLeft.append(l)
# return
return maxLeft # ~maxToLeft()
max_left = maxToLeft(nums)
max_right = maxToLeft(nums[::-1])
max_right = max_right[::-1]
print(nums)
print(max_left)
print(max_right)
"""
Original: [0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1]
Max Left: [-1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 3]
Max Right: [3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 2, -1]
"""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment