Answer to Question #204907 in Python for hgj

Question #204907

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


1
Expert's answer
2021-06-09T04:25:50-0400
#!/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))

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS