问题
I would like to know what is the minimum and maximum value this procedure can return in the following algorithm using the big-theta notation. The algorithm is:
procedure F(𝐴[1..n])
s = 0
for i = 1 to n
j = min(max(i,A[i]),n³)
s = s + j
return s
回答1:
EDIT: removed original answer as it was for the wrong question.
The analysis hinges on the following line:
min(max(i,A[i]),n³)
If we figure out the cases for this then we can easily figure the cases for the result. We must answer whether i > A[i] and then whether the greater of i and A[i] is greater than n^3.
i > A[i]andi > n^3. This cannot be the case becausei <= nandi, nare integers.i > A[i]andi < n^3. This can happen if, e.g.,A[i] = -1. In this case, we are addingitogether for0 <= i <= n. This comes out asn(n+1)/2, which isO(n^2). (I am usingObut Theta applies as well).i < A[i]andA[i] < n^3. This can happen ifi + 1<= A[i] <= n^3 - 1andn > 2. In this case, we are addingi + 1togetherntimes, foriequal1ton, or we are addingn^3 - 1togetherntimes. On the low end we getn(n-1)/2 - n, as before with the-nterm for the-1, and on the high end we getn^4 - n; somewhere betweenO(n^2)andO(n^4).i < A[i]andA[i] > n^3. This can happen ifA[i] > n^3. In this case we haven^3summedntimes forn^4,O(n^4).
Based on the above, my thinking is that the lower bound on the best case is Omega(n^2) and the upper bound on the worst case is O(n^4). Both of these bounds are tight for their respective cases, but since they are not the same we cannot give a single tight bound for the rate of growth of the result.
来源:https://stackoverflow.com/questions/42816454/algorithm-asymptotic-complexity