(Editors / moderators, please read my last comment on the selected answer to the question before deleting this one.)
Stack operations
In our first example of aggregate analysis, we analyze the stacks that were added to the new operation. Section 10.1 presents two basic operations of the stack, each of which takes O (1) time:
PUSH (S, x) pushes object x onto stack S.
POP (S) pops the top of the S stack and returns a pop-up object.
Since each of these operations is performed during O (1), we consider the cost of each of them 1. Thus, the total cost of the sequence of operations n PUSH and POP is n, and the actual operating time for n is therefore operation (n).
Now we add the stack operation MULTIPOP (S, k), which removes the k top objects of the stack S or pops the entire stack if it contains less than k objects. In the following pseudo-code, the STACK-EMPTY operation returns TRUE if there are no objects in the stack, otherwise FALSE.
What is the running time of MULTIPOP (S, k) on the stack of s objects? The actual runtime is linear in the number of POP operations actually performed, and therefore it is sufficient to analyze MULTIPOP in terms of abstract costs of 1 for PUSH and POP. The number of iterations of the while loop is the number of min (s, k) objects that jumped out of the stack. For each iteration of the loop, one call is made to the POP on line 2. Thus, the total cost of MULTIPOP is min (s, k), and the actual runtime is a linear function of this cost.
Let us analyze the sequence of operations n PUSH, POP and MULTIPOP on an initially empty stack. The worst cost of a MULTIPOP operation in a sequence is O (n), since the stack size is no more than n. In the worst case of any stack operation, therefore, O (n), and therefore a sequence of n operations costs O (n2), since we can have O (n) MULTIPOP operations evaluating O (n) each. Although this analysis is correct, the O (n2) result obtained by considering the worst cost of each operation separately is not dense.
Using aggregate analysis, we can get a better upper bound that takes into account the entire sequence of n operations. In fact, although a single MULTIPOP operation can be expensive, any sequence of n PUSH, POP, and MULTIPOP operations on an initially empty stack can cost no more than O (n). What for? Each object can be pushed no more than once for each click. Therefore, the number of times that a POP can be called on a non-empty stack, including calls inside MULTIPOP, is the largest number of PUSH operations that are at most n. For any value of n, any sequence of operations n PUSH, POP and MULTIPOP takes the total time O (n). The average transaction cost is O (n) / n = O (1). In an aggregate analysis, we assign the amortized cost of each transaction to an average cost. Therefore, in this example, all three stack operations have an amortized cost of O (1).