Skip to content

Instantly share code, notes, and snippets.

@mhamzawey
Last active December 17, 2018 22:18
Show Gist options
  • Save mhamzawey/00df394bc26a38ab31ff247896ae9a0f to your computer and use it in GitHub Desktop.
Save mhamzawey/00df394bc26a38ab31ff247896ae9a0f to your computer and use it in GitHub Desktop.
Get the maximum number in an array that is increasing then decreasing.
def get_max(arr, start, end):
# arr of size 1
if start == end:
return arr[start]
#arr of size 2, first element is larger than the second
if start == end + 1 and arr[start] >= arr[end]:
return arr[start]
#arr of size 2, second element is larger than the first
if end == start + 1 and arr[start] < arr[end]:
return arr[end]
#find the middle of the array
#compare the middle element to its adjacent elements
mid = (start + end)//2
#if arr[mid] is larger than it's adjacent elements (mid-1, mid-2_
# arr[mid] is the greatest element
if arr[mid] >= arr[mid + 1] and arr[mid] >= arr[mid - 1]:
return arr[mid]
#if arr[mid] greater than the right element and less than the left element
# we focus on the left side of the array and do the same logic of get_max()
if arr[mid] > arr[mid + 1] and arr[mid] < arr[mid - 1]:
return get_max(arr, start, mid-1)
# otherwise, we focus on the right array and do the same logic of get_max()
else:
return get_max(arr, mid + 1, end)
test_cases =[
[1, 3, 8, 15, 17, 9, 7, 2],
[1, 3, 8, 15, 17],
[3,2,5,6,7],
[10,9,8,7,6,5,4,3,2,1],
[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,6,5,4,3,2,1],
[1,2,3,4,5,6,7,8,9,10,10,9,8,7],
[1,1,1,1,1,1,1,1,1,1],
[-1,6,4]
]
for test_case in test_cases:
print(get_max(test_case,0,len(test_case)-1))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment