0
$\begingroup$

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)?

asked Aug 25, 2020 at 20:15
$\endgroup$
6
  • 1
    $\begingroup$ How many operations can computing $A[left]+...+A[right]$ be? $\endgroup$ Commented Aug 25, 2020 at 20:24
  • $\begingroup$ You're wrong; it matters. It is exactly what causes your confusion. $\endgroup$ Commented Aug 25, 2020 at 20:28
  • $\begingroup$ You have right-left-1 sums in the line that starts with Compute . This line is repeated by the inner for for right = left to n-1 and the outer for repeats its content for left=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 line Compute could 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$ Commented Aug 25, 2020 at 20:31
  • $\begingroup$ @BearAqua ok sure, let's assume the array length is n=8? $\endgroup$ Commented Aug 25, 2020 at 20:32
  • $\begingroup$ @plop sorry I am still a newbie, how do you get the formula n(n^2-3n-4)/6? thanks $\endgroup$ Commented Aug 25, 2020 at 20:40

0

Know someone who can answer? Share a link to this question via email, Twitter, or Facebook.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.