![]() |
VOOZH | about |
Given a queue of integers, the task is to write a program that efficiently finds the largest element in that queue. Return -1 if the queue is empty.
Examples:
Input: Queue = {15, 27, 18}
Output: 27
Explanation: Among 15(front), 27 and 18(back), 27 is the largest.Input: Queue = {12, 25, 29, 16, 32}
Output: 32
Explanation: Among 12(front), 25, 29, 16 and 32(back), 32 is the largest.
Naive Approach: The basic way to solve the problem is as follows:
The naive approach to finding the largest element in a queue is to just pop each element from the queue and store them in an array/vector. Then find largest element in that array.
Time Complexity: O(N), where N is the number of elements in the queue.
Auxiliary Space: O(N)
Efficient Approach: The efficient approach is to find the maximum/largest element of the queue during popping elements from the queue as follows:
- Store the current front element in the temp variable and then pop that element.
- Now, compare that temp with maxx and store the maximum value into maxx.
Below is the implementation of the above approach:
27
Time Complexity: O(N), where N is the number of elements in the queue.
Auxiliary Space: O(1)