0

In the following code, i know that the time complexity is O(n) but how do i proof it in a proper way? Is saying that searching array is O(n) enough?

int f[N];
F(n)
{
    if (f[n] >= 0) return f[n];
    f[n] = F(n-1) + F(n-2);
    return f[n];
}

int main()
{
    read n;
    f[0] = 0; f[1] = 1;
    for (i = 2; i <= n; i++)
        f[i] = -1;
    print F(n);
}
Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
Alejandro
  • 11
  • 4

1 Answers1

0

For each element of the array you call F. it may seem as a recursion to you but a bad implementation. each of the f[n-1] and f[n-2] calls actually just returns the values.

You will have 3n call to F(n), so still O(n).

If you are not obligated to recursion, you can program it with a single loop.

kelalaka
  • 5,064
  • 5
  • 27
  • 44