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

前端 未结 9 1090
傲寒
傲寒 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:17

    You can model the running time of the function as

    sum(sum(sum(Theta(1), k=i+1..j),j=i..n),i=1..n)
    

    As

    sum(sum(sum(1, k=i+1..j),j=i..n),i=1..n) = 1/6 n^3  - 1/6 n,
    

    the running time is Theta(n^3).

提交回复
热议问题