Algorithmic complexity of naive code for processing all consecutive subsequences of a list: n^2 or n^3?

前端 未结 9 1094
傲寒
傲寒 2020-12-25 11:41

I\'m studying for a test and found this question:

I can\'t really determine the complexity, I figured it\'s either O(n2) or O(n3) and I\'m lea

9条回答
  •  粉色の甜心
    2020-12-25 12:04

    The complete reasoning is as follows:

    Let n be the length of the array.

    1) There are three nested loops.

    2) The innermost loop performs exactly j-i iterations (k running from i+1 to j inclusive). There is no premature exit from this loop.

    3) The middle loop performs exactly n-j iterations (j running from i to n-1 inclusive), each involving j-i innermost iterations, in total (i-i)+(i+1-i)+(i+2-i)+... (n-1-i) = 0+1+2... + (n-1-i). There is no premature exit from this loop.

    4) The outermost loop performs exactly n iterations (i running from 0 to n-1 inclusive), each involving 0+1+2+ ... (n-1-i) innermost iterations. In total, (0+1+2... n-1) + (0+1+2+... n-2) + (0+1+2+... n-3) + ... (0). There is no premature exit from this loop.

    Now how do handle handle this mess ? You need to know a little about the Faulhaber's formula (http://en.wikipedia.org/wiki/Faulhaber%27s_formula). In a nutshell, it says that the sum of integers up to n is O(n^2); and the sum of the sum of integers up to n is O(n^3), and so on.

    If you recall from calculus, the primitive of X is X^2/2; and the primitive of X^2 is X^3/3. Every time the degree increases. This is not by coincidence.

    Your code runs in O(n^3).

提交回复
热议问题