write a function that takes an array of integers as input and prints the second maximum difference between any two elements from an array in python
#!/usr/bin/env python3
def secondMaxDiff(numbers):
"""
Calculates the second maximum difference between any two elements from
an array. If array contains less than three elements returns 0.
>>> secondMaxDiff([-4, 2, 4, 1, 11, 3, 0])
11
>>> secondMaxDiff([])
0
>>> secondMaxDiff([42])
0
>>> secondMaxDiff([-3, 1])
0
"""
diff1, diff2 = 0, 0
cnt = len(numbers)
for i in range(cnt-1):
for j in range(i+1, cnt):
diff = abs(numbers[i] - numbers[j])
if diff > diff1:
diff1, diff2 = diff, diff1
elif diff > diff2:
diff2 = diff
return diff2
# Driver code
if __name__ == '__main__':
arr = [-4, 2, 4, 1, 11, 3, 0]
# Prints 11
print(secondMaxDiff(arr))
Comments
Leave a comment