Algorithms with C# · Lesson 25

Keeping the largest k values with a min-heap

Discard the smallest retained candidate as each new value arrives.

How it works

To retain the largest k values from a stream, keep a min-heap containing at most k candidates. The smallest retained candidate is at the front. After adding a new value, remove the smallest if the heap is too large. Values too small to belong in the final top group are discarded naturally.

The sample retains nine, eight, and seven from six input values. The priority equals the value, so PriorityQueue behaves as the required min-heap. The final UnorderedItems view is explicitly sorted in descending order for display; the heap's internal storage arrangement is not a presentation contract.

After each iteration, the heap contains the largest permitted number of values seen so far. Duplicates are retained as separate observations, which is appropriate when the task asks for the largest k elements rather than k distinct values. If uniqueness is required, add a separate equality policy and test how it interacts with capacity.

This strategy uses storage proportional to k and usually work proportional to the input count times the logarithm of k. It can be useful when k is much smaller than a large source. Sorting the full source may be simpler for a small already materialized collection, so choose based on the actual access and output requirements.

Practice with count one, count zero, count larger than the source length, repeated maxima, and negative values. Add validation for a negative count instead of letting an invalid capacity policy produce confusing behavior. Predict both the retained count and the final sorted contents.

Finally, adapt the heap to records with a score and an identifier. Define a complete tie policy if exactly k records must be chosen reproducibly. Priority ties do not automatically preserve arrival order, so deterministic business selection requires more than placing the numeric score in the priority slot.

A working example

using System;
using System.Linq;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading;
using System.Threading.Tasks;
using System.Runtime.CompilerServices;

int[] values = { 4, 1, 9, 3, 7, 8 }; int count = 3;
var heap = new PriorityQueue<int, int>();
foreach (int value in values) {
    heap.Enqueue(value, value);
    if (heap.Count > count) heap.Dequeue();
}
Console.WriteLine(string.Join(",", heap.UnorderedItems.Select(item => item.Element).OrderByDescending(value => value)));

Expected output

9,8,7
Try this
Heap storage is not sorted display order; sort the retained result explicitly.