Enhances 'base case' logic (#227)

Original function does not work when input array is empty or contains a single value. In the revised code, base case has been augmented to support those. Works successfully for all these test cases: find_max([1, 12, 8, 5]), find_max([]), find_max([1])
This commit is contained in:
Udit Gupta
2022-11-18 13:47:57 -08:00
committed by GitHub
parent 3f02143f7f
commit 308148653a

View File

@@ -1,5 +1,9 @@
def find_max(arr):
if len(arr) == 2:
if len(arr) == 0:
return 0
elif len(arr) == 1:
return arr[0]
elif len(arr) == 2:
return arr[0] if arr[0] > arr[1] else arr[1]
sub_max = find_max(arr[1:])
return arr[0] if arr[0] > sub_max else sub_max
return arr[0] if arr[0] > sub_max else sub_max