Code Logo

Priority Queue Max

Published at25 Jul 2026
Priority Queue Easy 0 views
Like0

Given an array representing a priority queue (max-heap), return the maximum element without removing it. In a max-heap priority queue, the largest element is always at the root (index 0).

For example, the maximum of [9, 7, 5, 3, 1] is 9. The maximum of [10, -5, 0] is 10. If the array is empty, return 0. The operation does not modify the priority queue.

Peeking at the maximum is a fundamental priority queue operation. It allows you to inspect the highest-priority (largest) element without removing it. This is useful in scheduling (next task with highest priority), event-driven simulation (next event with latest time), and online algorithms that need to track the current maximum.

In a max-heap, the root at index 0 is always the largest element. This is guaranteed by the heap invariant: every parent node is greater than or equal to its children. Therefore, peeking at the maximum is an O(1) operation — just return the first element of the array.

Edge cases include an empty priority queue (return 0), a single-element queue (return that element), and a queue with all equal values (return that value). The heap structure ensures the maximum is always at the root.

Example Input & Output

Example 1
Input
[]
Output
-1
Explanation

Empty

Example 2
Input
[3,1,4,1,5]
Output
5
Explanation

Max is 5

Example 3
Input
[42]
Output
42
Explanation

Single

Example 4
Input
[10,5,7]
Output
10
Explanation

Max is 10

Example 5
Input
[-5,-2,-10]
Output
-2
Explanation

Max negative

Algorithm Flow

Recommendation Algorithm Flow for Priority Queue Max
Recommendation Algorithm Flow for Priority Queue Max

Solution Approach

Return the first element of the array, which is the root of the max-heap.

function solution(arr) {
  return arr.length > 0 ? arr[0] : 0;
}

In a max-heap array, the largest element is always at index 0 (the root). Return it if the array is not empty. If the array is empty, return 0 as a sentinel value. This works because the heap invariant guarantees that every parent is greater than or equal to its children, so the maximum always resides at the root regardless of how many insertions or extractions have been performed.

Time complexity is O(1), space complexity is O(1).

Best Answers

java
class Solution {
    public int solution(int[] nums) {
        if(nums.length==0)return -1;int m=nums[0];for(int n:nums){if(n>m)m=n;}return m;
    }
}