You are given an array of N integers, find the Max Difference where the index of largest number is greater than the index of the smallest number. If not find the next smallest number, so on and so forth. If this condition cannot be met, return -1
Sample Input Sample Output
values = [1, 2, 3, 4, 5] 4
values = [2, 3, 4, 5, 1] 3
values = [121, 30, 45, 55, 1] -1
My solution, Python 2.7
def findNewIndex(max_index, min_index, input_array):
input_array.pop(min_index)
num = min(input_array)
min_index = input_array.index(num)
if max_index > min_index:
return input_array[max_index] - input_array[min_index]
elif max_index < min_index and input_array:
return findNewIndex(max_index, min_index, input_array)
else:
return -1
def maxDifference(input_array):
max_num = max(input_array)
max_index = input_array.index(max_num)
min_num = min(input_array)
min_index = input_array.index(min_num)
if max_index > min_index:
print input_array[max_index] - input_array[min_index]
else:
ans = findNewIndex(max_index, min_index, input_array)
print ans
I'd like feedback on the solution, is this a good way to solve it? Any improvements I can make to the code in terms of performance/style?
-1
because the largest number is121
and it's index0
all the other numbers have a higher index, therefore the answer is-1
\$\endgroup\$