$\begingroup$
$\endgroup$
6
I recently came across a function called the strawman algorithm which the pseudo code looks like this:
StrawmanSubarray(A):
Initialize bestsum = A[0]
For left=0 to n-1:
For right = left to n-1:
Compute sum A[left] + . . . + A[right]
If sum > bestsum: bestsum = sum
The time complexity is Θ (n^3), and I don't quite get where is the 3rd n comes from to get Θ (n^3)?
right-left-1sums in the line that starts withCompute. This line is repeated by the innerforforright = left to n-1and the outer for repeats its content forleft=0 to n-1. So, the number of sums is $\sum_{l=0}^{n-1}\sum_{r=l}^{n-1}(r-l-1)=\frac{n (n^2 - 3 n - 4)}{6}$. However, the lineComputecould be implemented in such a way that each iteration does only one sum. In this case the number of sums is $\sum_{l=0}^{n - 1}( \sum_{r=l}^{n - 1} 1) = \frac{n (n + 1)}{2}$. $\endgroup$