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

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

    O(n^3).

    You have calculated any two item between arr[0] and arr[arr.length - 1], running by "i" and "j", which means C(n,2), that is n*(n + 1)/2 times calculation.

    And the average step between each calculation running by "k" is (0 + arr.length)/2, so the total calculation times is C(n, 2) * arr.length / 2 = n * n *(n + 1) / 4, that is O(n^3).

提交回复
热议问题