Greedy with heaps
30 min · Advanced
Need help? Ask a tutor on WhatsApp (opens in a new tab)Priority queues maintain dynamic greedy choices efficiently when problem state evolves during execution.
Dynamic greedy decisions with priority queues
When candidates are static, sorting once at the start is sufficient. However, many problems create new candidates or modify values dynamically. Re-sorting after each decision takes quadratic time.
A priority queue retrieves and inserts elements in logarithmic time. This allows greedily picking the minimum or maximum among evolving options.
Step by step
Step 1 of 4
- stepCost
- 10
- totalCost
- 10
Heaps prevent recalculating candidate rankings from scratch. Total execution time stays bounded by log-linear complexity.
Optimal merge patterns and Huffman coding
Connecting ropes combines items two at a time. The cost to join two ropes equals the sum of their lengths. Because intermediate sums participate in future joins, smaller lengths should merge first.
Example 1 · Brute force: re-sort the list after every join, O(n^2 log n)
import java.util.*;
public class Main { public static void main(String[] args) { List<Integer> sticks = new ArrayList<>(Arrays.asList(8, 4, 6, 12)); int total = 0; while (sticks.size() > 1) { Collections.sort(sticks); // full sort every round int cost = sticks.remove(0) + sticks.remove(0); total += cost; sticks.add(cost); } System.out.println("Total connection cost: " + total); }}Total connection cost: 58
What this code does
- The two smallest sticks must be joined first, so the list is sorted again after each new stick is added.
- A full sort per round is O(n log n), and there are n - 1 rounds.
- A min-heap gives the two smallest in O(log n) and accepts the new stick in O(log n).
Example 2 · Optimal: min-heap, O(n log n) time, O(n) space
import java.util.PriorityQueue;
public class ConnectSticksDemo { public static int connectSticks(int[] sticks) { PriorityQueue<Integer> pq = new PriorityQueue<>(); for (int s : sticks) { pq.offer(s); } int totalCost = 0; while (pq.size() > 1) { int first = pq.poll(); int second = pq.poll(); int cost = first + second; totalCost += cost; pq.offer(cost); } return totalCost; }
public static void main(String[] args) { int[] sticks = {8, 4, 6, 12}; System.out.println("Total connection cost: " + connectSticks(sticks)); }}Total connection cost: 58
What this code does
- Min-heap extracts 4 and 6, merging into 10 with total cost 10.
- Next, merges 8 and 10 into 18, increasing total cost to 28.
- Finally, merges 12 and 18 into 30, finishing with total cost 58.
- A heap pops the two smallest sticks in O(log n) and accepts the new stick in O(log n), so no full sort is repeated.
Example 3 · Huffman Coding Prefix Tree
import java.util.PriorityQueue;
public class HuffmanTreeDemo { static class Node implements Comparable<Node> { char ch; int freq; Node left, right; Node(char ch, int freq) { this.ch = ch; this.freq = freq; } Node(int freq, Node left, Node right) { this.ch = '-'; this.freq = freq; this.left = left; this.right = right; } public int compareTo(Node o) { return Integer.compare(this.freq, o.freq); } }
public static Node buildTree(char[] chars, int[] freqs) { PriorityQueue<Node> pq = new PriorityQueue<>(); for (int i = 0; i < chars.length; i++) { pq.offer(new Node(chars[i], freqs[i])); } while (pq.size() > 1) { Node a = pq.poll(); Node b = pq.poll(); pq.offer(new Node(a.freq + b.freq, a, b)); } return pq.poll(); }
public static void main(String[] args) { char[] chars = {'a', 'b', 'c', 'd'}; int[] freqs = {5, 9, 12, 13}; Node root = buildTree(chars, freqs); System.out.println("Root frequency sum: " + root.freq); }}Root frequency sum: 39
What this code does
- Fuses lowest frequencies 5 ('a') and 9 ('b') into parent with sum 14.
- Fuses 12 ('c') and 13 ('d') into parent with sum 25.
- Fuses 14 and 25 to create the final tree root with total frequency 39.
A min-heap extracts the two shortest ropes repeatedly. Their sum is added to total cost and reinserted into the heap. Huffman coding uses the exact same bottom-up merge principle. It compresses text by assigning shorter binary codes to frequent characters. A min-heap pairs the two lowest-frequency trees until one root remains. Frequent characters remain near the tree root with compact binary codes.
Order of execution
Optimal merge with a heap
Tap the steps of the optimal merge loop in order.
Capital maximisation and project selection
In project capital problems, you start with initial funds W. Each project has a capital requirement and an expected profit. You can choose at most k projects to maximise final capital.
Example 4 · Maximum Capital (IPO)
import java.util.Arrays;import java.util.PriorityQueue;
public class IpoCapitalDemo { public static int findMaximizedCapital(int k, int w, int[] profits, int[] capital) { int n = profits.length; int[][] projects = new int[n][2]; for (int i = 0; i < n; i++) { projects[i][0] = capital[i]; projects[i][1] = profits[i]; } Arrays.sort(projects, (a, b) -> Integer.compare(a[0], b[0]));
PriorityQueue<Integer> maxProfit = new PriorityQueue<>((a, b) -> Integer.compare(b, a)); int ptr = 0;
for (int step = 0; step < k; step++) { while (ptr < n && projects[ptr][0] <= w) { maxProfit.offer(projects[ptr][1]); ptr++; } if (maxProfit.isEmpty()) break; w += maxProfit.poll(); } return w; }
public static void main(String[] args) { int[] profits = {1, 2, 3}; int[] capital = {0, 1, 1}; System.out.println("Max capital: " + findMaximizedCapital(2, 0, profits, capital)); }}Max capital: 4
What this code does
- Starts with capital 0 and chooses project with capital 0 and profit 1 (capital becomes 1).
- Capital 1 unlocks projects requiring capital 1. Chooses project with profit 3.
- Final capital reaches 0 + 1 + 3 = 4.
Among all projects you can afford, choosing the highest profit is optimal. However, completing a project increases W, unlocking newly affordable projects. Sort projects by required capital in ascending order. Maintain a max-heap storing profits of currently affordable projects. Push all affordable projects into the heap as capital expands. Extract the highest profit project and add its payout to W. Repeat this greedy selection k times in log-linear time.
Next step
Check your understanding
10 quick questions