119k views
0 votes
Write a method that, given a non-empty queue of integers, returns the largest value. The queue should have the same contents as before the call. You can remove elements to inspect them but need to add them back into the queue.

a) findMax(queue)

b) getMax(queue)

c) largestValue(queue)

d) retrieveLargest(queue)

User DJPB
by
6.9k points

1 Answer

4 votes

Final answer:

The correct method to find the largest value in a non-empty queue of integers while keeping the queue unchanged is option b) getMax(queue).

Step-by-step explanation:

The correct method to find the largest value in a non-empty queue of integers while keeping the queue unchanged is option b) getMax(queue).

To implement this method, you would need to iterate through the queue, keeping track of the maximum value encountered. You can remove elements from the queue to compare them but need to add them back afterwards.

Here is a possible implementation in Java:

public int getMax(Queue<Integer> queue) {
int max = Integer.MIN_VALUE;

// Iterate through each element in the queue
for (int num : queue) {
if (num > max) {
max = num;
}
}

// Add all the elements back into the queue
while (!queue.isEmpty()) {
queue.offer(queue.poll());
}

return max;
}

User Savan Gadhiya
by
7.5k points