简体   繁体   English

计算最大子序列和的时间复杂度

[英]Calculating Time Complexity of Maximum Subsequence Sum

Hello everyone I trying to calculate the time complexity of Maximum Subsequence Sum. 大家好,我试图计算最大子序列和的时间复杂度。 Actually I know the answer which is O(n^3) and it follows from the function (n^3 + 3n^2 + 2n)/6 实际上我知道答案是O(n ^ 3),它是从函数(n ^ 3 + 3n ^ 2 + 2n)/ 6得出的

My question is how is that function obtained. 我的问题是如何获得该功能。 在此处输入图片说明

Quite simply, actually: just look at the loops in the code. 实际上,这很简单:只需查看代码中的循环即可。

for (int i=0; i<n; i++)
    for(j = i; j<n; j++) {
        ...
        for (int k=i; k<=j; k++)
            XXX;

The line XXX is executed n^3 times (modulo some constant factor and some lower powers of n ), since the outer loop obviously runs from 0 to n-1 , the "middle" loop runs from i (which will start out with 0 , 1 , ...) to n-1 , meaning that the inner loop will be "started" approx n^2 times. XXX行执行了n^3次(以一定的常数和n低次幂为模),因为外循环显然从0开始运行到n-1 ,“中间”循环从i开始运行(将从0开始, 1 ,...)到n-1 ,这意味着将“开始”内循环大约n^2次。 Now, both i and j depend on n (eg., i will be 0 and j=n-1 at the end of the first outer iteration), so line XXX will be n times (for the inner loop) by n^2 times (for the outer two loops), resulting in a total of n^3 . 现在, ij依赖于n (例如,在第一次外部迭代结束时, i将为0j=n-1 ),因此,第XXX行将为n倍(对于内部循环)为n^2次(对于外部两个循环),总共为n^3

To get the concrete function (n^3 + 3n^2 + 2n)/6 , you'd have to be more thorough in your calculation and take care of all those factors I simply omitted above. 要获得具体函数(n^3 + 3n^2 + 2n)/6 ,您必须更全面地进行计算,并照顾好我在上文中省略的所有因素。

Here is how.. 这是怎么..

i=0
j=0 k=0              (count=1 )
j=1 k=0,1            (count =2)
j=2 k=0,1,2          (count = 3)
...
j=n-1 k=0,1,2,...n-1  (count = n)

Total number of times code executed = 1+2+3+...+n =  n(n+1)/2

i=1
j=1 k=1              (count=1 )
j=2 k=1,2            (count =2)
j=3 k=1,2, 3          (count = 3)
...
j=n-1 k=1,2,...n-1  (count = n-2)

Total number of times code executed = 1+2+3+...+n-1 =  (n-1)n/2

...

i=n-1
j=n-1 k=n-1     ( count = 1)
Total number of  of times code executed = 1 = 1(1+1)/2


 Now if we sum for all the values of i

 n(n+1)/2 + ((n-1)((n-1)+1)/2+.....+1(1+1)/2

 =∑ N(N+1)/2 =1/2∑(N^2 +N) =1/2(∑N^2+∑N)=1/2{  1/6  N(N+1)(2N+1) + 1/2 N(N+1) } =1/2{ (2N^3 + 3N^2+N )/6 +(N^2+N)/2} =(N^3 + 3N^2 + 2N)/6

检查马克·艾伦·韦斯(Mark Allen Weiss)(在他的书中)建议的解决方案

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM