【python公司校招题】

【python吉比特】最大差值?

2019-08-11  本文已影响0人  阿牛02

题目:给定一个未排序的数列,找到此数列在已排序状态下的两个相邻值的最大差值,少于两个值时返回0。例如:给定数列 [1,3,2,0,1,6,8] 则 最大差值为3。注意:请尽量使用时间复杂度为O(n)的方案。

输入描述:

第一行输入单个整数N作为数列的大小,第二行输入所有数列中的元素M,共N个。0 < N <= 1000000, 0 < M < 2100000000

输出描述:

数列的最大差值。

示例1

输入

3

1 10 5

输出

5

code:

def sortMax(lists):

    if len(lists) < 2:

        return 0

    maxValue = 0

    i = 0

    while i < len(lists) - 1:

        if lists[i + 1] - lists[i] > maxValue:

            maxValue = lists[i + 1] - lists[i]

        i += 1

    return maxValue

if __name__ == "__main__":

    N = 3

    lists = [1, 10, 5]

    lists = sorted(lists)

    print(sortMax(lists))

上一篇 下一篇

猜你喜欢

热点阅读