I need to find the maximum difference between elements in an unsorted list if the element to the right of the present element is greater. For eg:
myList = [2, 3, 8, 0, 7].
Function should calculate as follows:
present element = 2.
is 3 > 2? Yes. Then 3-2 = 1
is 8 > 2? Yes. Then 8-2 = 6
is 0 > 2? No. Go to the next element.
is 7 > 2? Yes. Then 7-2 = 5 and so on
Finally my output = 7
My first solution is as follows:
def maxDiff(a):
l = len(a)
arr = []
for i in range(l-1):
for j in range(i+1, l):
if a[j] > a[i]:
diff = a[j] - a[i]
arr.append(diff)
return (max(arr))
I was said that this is not an optimal solution. I came up with another solution which is as follows:
def maxDiff(a):
l = len(a)
diffList = []
for i in range(l-1):
newList = a[i+1:]
max1 = max(newList)
difference = max1 - a[i]
diffList.append(difference)
return (max(diffList))
My question is is the second solution correct? If yes, then is it optimal? What is the time complexity of both these functions? Is there any other solution that is more optimal?