平均时间复杂度_【干货】算法 | max函数的平均时间复杂度

本文详细探讨了max函数在所有可能的数组排列下,平均运行时间的计算方法。通过对每轮迭代中最大值更新概率的分析,利用指示随机变量Xi来表示更新发生的次数,得出总期望更新次数与调和数的关系,从而推导出max函数在平均情况下的时间复杂度为 nth 几何数。内容由CUCS学术部梁力天撰写,CUCS宣传部编辑。
摘要由CSDN通过智能技术生成
a20cac1390a3e70f05c47b5fcdbfc2b0.png

Proof of 

average running time of max()

recall that the code for max:

def maximum(A, n):     # # of RAM operations, type of operation        v = float('-inf')  # 1, Assigning a value        for i in range(n): # 3n + 1,                       #   n Arithmetic operation (i + 1)                       #   n Assigning a value (i = i + 1)                       #   n + 1 Comparison operation (i < n)                            if A[i] > v:   # n, Comparison operation            v = A[i]   # X,                       #   a random variable X that has (0 < X <= 2n)    return v           # 1

Assume

  1. all possible orderings are equally likely (meaning each value has a equall probability being the largest value of the subarray A[0-i])

  2. all n elements of A are distinct

  3. update takes O(1)

Key idea

The running maximum gets updated on iteration i if and only if max([A[0] ... A[i]]) = A[i]. Since the probability of each value being the largest value of the subarray is known, we can calculate the total expected update count of this algorithm.

Set up indicator random variable Xi

if v updated on iteration i 

Xi = 1

else

Xi = 0

The distribution of Xi

589f1e313a3d951f70428143035347a2.png

The Expectation of Xi

e503a85291baad903287ece5877a7614.png

Total exact updates

0db33ab02fd41594787257cc3c859aaa.png

Total expected updates

915074d8d8763572cab012cd1d8d6705.png

which reduce to the nth harmonic number

eb0e69cce31ffac73f3bfa15fbec62ec.png

because (gamma is Euler's constant)

2a0038f39d285683382bbc6872eab2a0.png

The average case running time T(n) of max(A, n) is

e93851998c9e7122285e1735fbe8a9a4.png

文案 / CUCS学术部 梁力天

编辑 / CUCS宣传部

© CUCS 2020.10

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值