There exist such a structure that acts like a queue but lets you retrieve min/max value in constant time, actually not strictly constant, it is amortized constant time (named min/max queue as you could guess). There are two ways of implementing it - using two stacks or using a queue and a deque.
Deque implementation looks more less like this (language agnostic):
so we have a deque of max elements, the one on the front is the desired max, and a standard queue.
Push operation
- If the queue is empty, just push the element on both, the queue and the deque.
- If the queue is not empty, push the element on the queue, going from the back of the deque delete all elements that are strictly less than the one we are now pushing (they will surly not be the max, since the pushed element is larger and will last on the queue for longer) and push the current element on the back of the deque
Remove operation
- If the front of the deque is equal to the front of the queue then pop both (deque from the front)
- If the front of the deque is not equal to the front of the queue then pop just the queue, the poped element surely is not the largest one.
Get max
- It is just the first element of the deque.
(lots of arguments should be added to make it clear why it works, but the second version presented below may be the answer to this necessity)
The Stack implementation is quite similar, I think it may be a bit longer to implement but perhaps easier to grasp. The first thing to note is that it is easy to store the maximal element at the stack - easy exercise (for the lazy ones - Stack with find-min/find-max more efficient than O(n)?). The second part, perhaps a bit tricky if seen the first time, is that it is quite easy to implement a queue using two stacks, it can be found here - How to implement a queue using two stacks? . And that is basically it - if we can get the maximal element of both of the stacks we can get the maximal element of the whole queue (taking maximum is associative or something like that if you want a more formal argument, but I bet you don't, it is really obvious).
The min versions is done analogically.
Everything may also be done using a set (or something of it's kind) in O(nlogn) time but it is pointless as the constant in O(n) is really small and it should be much faster, yet easy to implement.
NON-INTERESTING parts from the first version:
Hope I helped a little bit. And hope that didn't say anything wrong. Can give a simple implementation in C++/C if required. Would be grateful for any feedback on the form as it is my first post of this type anywhere :) (and English is not my native language). Also some confirmation on the correctness would be great.
EDIT: as this answer got me some points I felt obliged to clean it up a bit, also extending it a bit.