Stacks & Queues

Answer & solution
Official answer: 256.0 : 256.0
Our answer: 256
Let F(n) be the maximum number of loop iterations with n queued values and no relevant stack entries. Until a minimum queued value is pushed, each value originally preceding that minimum is pushed at most once and popped at most once: popped items return behind the minimum. Thus this phase costs at most 2n−1 iterations. Once the minimum is pushed it never pops, leaving at most n−1 values to process above it. Hence F(n)≤2n−1+F(n−1), giving F(n)≤n². A strictly descending initial queue attains equality at each phase, because all preceding values are pushed and popped and return in descending order behind the minimum. Therefore F(16)=256.
Each loop iteration moves one item either from Q to S or from S to Q. For a descending input 16,15,...,1, the first phase moves 15 earlier values onto the stack and back off before finally pushing 1:31 moves. That 1 never leaves, and the remaining values are again descending, giving phases 29,27,...,1. Their sum is 162=256. The upper-bound argument counts at most one push and one pop before the next minimum is fixed, so the example achieves the maximum rather than merely a large runtime.