Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the space complexity of this algorithm O(n)?

This is the algorithm for finding the maximum contiguous sub-sequence sum using the DP approach. The algorithm seems to be quite okay but it was mentioned that this has space complexity O(n). Why?

To me it seems this algorithm has O(1) space complexity. Another thing that I want to ask is that in case of algorithms which do not use recursion of any sort, can it still be possible for it to have anything other than a constant space complexity?

Create arrays S and T each of size n.
    S[0] = A[0];
    T[0] = 0;
    max = S[0];
    max_start = 0, max_end = 0;

    For i going from 1 to n-1:
    // We know that S[i] = max { S[i-1] + A[i], A[i] .
         If ( S[i-1] > 0)
           S[i] = S[i-1] + A[i];
           T[i] = T[i-1];

         Else
           S[i] = A[i];
           T[i] = i;

         If ( S[i] > max)
           max_start = T[i];
           max_end = i;
           max = S[i];
    EndFor.

Output max_start and max_end
like image 698
bigbong Avatar asked Nov 07 '13 07:11

bigbong


1 Answers

The first line says it all:

Create arrays S and T each of size n.

Arrays of size n require Θ(n) space, so your algorithm automatically uses Ω(n) space. Looking over the rest of the algorithm, you can see that only O(1) other variables are used and that there's no recursion, so the total space used is Θ(n).

In general, the space complexity of an algorithm depends on the number of local variables used but also their sizes. Arrays, maps, sets, trees, etc. take up space proportional to the number of elements they hold, so if you only have a constant number of variables used you can still use more than O(1) space if they end up storing multiple elements.

Hope this helps!

like image 71
templatetypedef Avatar answered Nov 15 '22 06:11

templatetypedef