Max heap
Beginner · 6 min · code in PHP, JavaScript, Java and Go
Where you will meet this in real life
A max heap is the mirror of a min heap: the biggest item is always on top and every parent is bigger than its children. It is the right tool when you keep needing the highest, largest or most important item as data changes.
Practical use cases
- Web app: Always knowing the highest bid. An auction page must show the current highest bid the moment a new one arrives. Bids are stored in a max heap, so the top is always the winner so far. Even during a last-minute rush of thousands of bids, the page shows the leader instantly.
- Web app: Live top score on a cricket-style leaderboard. A fantasy-cricket app updates points after every ball. The max heap keeps the highest scorer on top so the "Leader" badge changes immediately. The app does not re-sort all players after each ball. Fans watching the match see the badge move the moment the points change.
- System: Heap sort and job priorities. Heap sort repeatedly takes the biggest item from a max heap to sort a list. Operating systems and job systems also use max heaps when a higher number means a more urgent task that must run first. The top of the heap is always the next thing to run.
The story: The Orange Cap Race
During the school cricket week, Kabir kept a notebook for the "Orange Cap", the prize for the highest run-scorer. Every evening new scores came in, and every evening he scribbled over the old list to find the top batter. Mira peeked at the messy pages and laughed.
"Remember Grandpa's family tree for the cheapest quote? Do the opposite. Make the highest scorer the grandfather. Under every player, hang two players who scored no more than them."
Kabir drew it: 90 at the top, then 70 and 80, then 40, 50, 60 and 30. Whichever parent he checked, it had more runs than its children. When a player with 85 runs was hung under 80, Mira shouted, "Wrong! That child beats its parent!" They fixed it, and the Orange Cap holder was always the top of the tree, one glance away.
That mirror image of the min heap has a name too: the max heap. Same shape, same array trick, opposite rule.
How to spot this problem, and where you need it
You constantly need the highest or most important value from data that keeps changing, and you do not want to re-scan or re-sort it every time.
Signs you need it
- You use max() on a big array on every update to find the top item.
- Words like "largest first", "highest priority", "top bid" or "most urgent" appear in the task.
- You only need the single best item right now, not a fully sorted list.
Where to use it in a project
- Auction, trading and leaderboard features that always highlight the current highest value.
- Job systems where a larger priority number means run it sooner.
The solution
Keep the items in an array that acts like a tree and apply one rule: every parent is at least as big as its children. The biggest value is then always at the first position. When you add a value, put it at the end and swap it upward while it beats its parent. When you remove the top, move the last item up top and swap it downward.
Payoff: Before: re-scanning all 20,000 bids on each new one. After: the leader is read in one step and updated in a handful of swaps.
Explain it like I am 8
It is the same pyramid as before, but now the tallest kid stands on top, and every kid is taller than the two kids standing under them. Find the tallest kid? Look at the top!
How it works, step by step
- A max heap is a tree where every parent is bigger than or equal to its children.
- It fills each row from left to right, so it also fits neatly into an array.
- The biggest value is always the root, the first box of the array.
- To check a heap, look at each parent and its two children:
parent >= childmust hold everywhere. - Need a max heap but only have a min-heap tool? Store the numbers with their sign flipped (5 becomes -5) and flip back when you read them.
The code in four languages
PHP
<?php
// $outranks(parent, child) must be true for every parent/child pair.
function isHeap(array $a, callable $outranks): bool {
$n = count($a);
for ($i = 0; $i < $n; $i++) {
foreach ([2 * $i + 1, 2 * $i + 2] as $child) { // the two children of spot $i
if ($child < $n && !$outranks($a[$i], $a[$child])) return false;
}
}
return true;
}
$runs = [90, 70, 80, 40, 50, 60, 30];
$maxRule = fn($p, $c) => $p >= $c; // max heap: parent at least as big
$minRule = fn($p, $c) => $p <= $c; // min heap: parent at most as big
echo 'max heap? ', isHeap($runs, $maxRule) ? 'yes' : 'no', PHP_EOL; // yes
echo 'min heap? ', isHeap($runs, $minRule) ? 'yes' : 'no', PHP_EOL; // no
echo 'Orange cap holder: ', $runs[0], PHP_EOL; // 90
echo 'with 85 under 80? ', isHeap([90, 70, 80, 40, 50, 85, 30], $maxRule) ? 'yes' : 'no', PHP_EOL; // noJavaScript
// outranks(parent, child) must be true for every parent/child pair.
function isHeap(a, outranks) {
const n = a.length;
for (let i = 0; i < n; i++) {
for (const child of [2 * i + 1, 2 * i + 2]) { // the two children of spot i
if (child < n && !outranks(a[i], a[child])) return false;
}
}
return true;
}
const runs = [90, 70, 80, 40, 50, 60, 30];
const maxRule = (p, c) => p >= c; // max heap: parent at least as big
const minRule = (p, c) => p <= c; // min heap: parent at most as big
console.log('max heap? ' + (isHeap(runs, maxRule) ? 'yes' : 'no')); // yes
console.log('min heap? ' + (isHeap(runs, minRule) ? 'yes' : 'no')); // no
console.log('Orange cap holder: ' + runs[0]); // 90
console.log('with 85 under 80? ' + (isHeap([90, 70, 80, 40, 50, 85, 30], maxRule) ? 'yes' : 'no')); // noJava
import java.util.function.BiPredicate;
public class Main {
// outranks(parent, child) must be true for every parent/child pair.
static boolean isHeap(int[] a, BiPredicate<Integer, Integer> outranks) {
int n = a.length;
for (int i = 0; i < n; i++) {
for (int child : new int[]{2 * i + 1, 2 * i + 2}) { // the two children of spot i
if (child < n && !outranks.test(a[i], a[child])) return false;
}
}
return true;
}
public static void main(String[] args) {
int[] runs = {90, 70, 80, 40, 50, 60, 30};
BiPredicate<Integer, Integer> maxRule = (p, c) -> p >= c; // max heap: parent at least as big
BiPredicate<Integer, Integer> minRule = (p, c) -> p <= c; // min heap: parent at most as big
System.out.println("max heap? " + (isHeap(runs, maxRule) ? "yes" : "no")); // yes
System.out.println("min heap? " + (isHeap(runs, minRule) ? "yes" : "no")); // no
System.out.println("Orange cap holder: " + runs[0]); // 90
System.out.println("with 85 under 80? " + (isHeap(new int[]{90, 70, 80, 40, 50, 85, 30}, maxRule) ? "yes" : "no")); // no
}
}Go
package main
import "fmt"
// isHeap checks that outranks(parent, child) is true for every parent/child pair.
func isHeap(a []int, outranks func(parent, child int) bool) bool {
n := len(a)
for i := 0; i < n; i++ {
for _, child := range []int{2*i + 1, 2*i + 2} { // the two children of spot i
if child < n && !outranks(a[i], a[child]) {
return false
}
}
}
return true
}
func yesNo(b bool) string {
if b {
return "yes"
}
return "no"
}
func main() {
runs := []int{90, 70, 80, 40, 50, 60, 30}
maxRule := func(p, c int) bool { return p >= c } // max heap: parent at least as big
minRule := func(p, c int) bool { return p <= c } // min heap: parent at most as big
fmt.Println("max heap?", yesNo(isHeap(runs, maxRule))) // yes
fmt.Println("min heap?", yesNo(isHeap(runs, minRule))) // no
fmt.Println("Orange cap holder:", runs[0]) // 90
fmt.Println("with 85 under 80?", yesNo(isHeap([]int{90, 70, 80, 40, 50, 85, 30}, maxRule))) // no
}Time: O(1) to peek the maximum · Extra space: O(n). The biggest value is always the first box, so looking at it is instant.
Watch out for
- Mixing up the two rules. Min heap: parent smaller. Max heap: parent bigger. Write it on a sticky note.
- Thinking the second-biggest is always the second box. It is one of the root's two children, but you must compare them to know which.
- Forgetting that equal values are allowed: parent ≥ child, not strictly bigger.
Quick check
- Where is the largest value in a max heap?
- Always the right child
- At the root
- At the last leaf
- Which array is a valid max heap?
- [3, 9, 5]
- [9, 3, 5]
- [5, 9, 3]
- You only have a min-heap tool. How can you get max heap behaviour?
- Sort first
- It is impossible
- Store numbers with their sign flipped