Pick a fixed number of items from a large pool to maximize a set function f. If f is monotone — adding an item never
hurts — and submodular — the marginal gain of an item can only shrink as the set grows — then greedy achieves at least
1 − 1/e (about 63.2%) of the optimal value for a normalized objective (Nemhauser, Wolsey, and Fisher, 1978).
When evaluating a gain is expensive, a heap of cached upper bounds can save most of those evaluations while keeping
greedy’s guarantee. On the advertising benchmark below, lazy greedy needed 576 evaluations where a full scan needed
22,500.
up to k · n, scanning every remaining candidate per pick
1 − 1/e
none
Lazy greedy (Minoux, 1978)
n + re-evaluations of stale roots
1 − 1/e (unchanged)
a max-heap of cached upper bounds
Stochastic greedy
(n/k) · log(1/ε) per step
1 − 1/e − ε in expectation
an injected random source
Lazy greedy works because of submodularity itself: a cached marginal gain is an upper bound on the true gain now, so
the heap’s root is an upper bound on the best remaining choice. Re-evaluate the root. If the fresh value still beats
every other cached value, it is provably the maximum, so take it. If it dropped, put it back with its smaller value and
repeat. A candidate with a fresh gain below another candidate’s cached bound may be revisited before the next pick.
timeO(nc + r(c + log n)), where r counts heap iterations after initialization · spaceO(n), one cached gain per candidate · c is the cost of one marginal-gain evaluation
@param ― order - Total ordering over the elements.
@param ― items - Optional initial elements, in iteration order.
maxBinaryHeap,
constnumberOrder:Order<number>
A total order on number.
NaN is totally ordered as greater than every other number and equal
only to itself; 0 equals -0. Making the order total, rather than
returning 0 for every NaN comparison the way </> do, is what lets
heaps containing NaN keep a coherent invariant: with the partial rule,
NaN would compare equal to both 1 and 3 while 1 < 3, and a sift
could strand a smaller number behind it. NaN therefore drains last
from a min heap and first from a max heap.
Under this order -Infinity is the least element and NaN the greatest,
so the full chain reads -Infinity < -0 = 0 < 1 < Infinity < NaN.
numberOrder } from'knotkit/heap'
// Each candidate reaches some users; pick the two that reach the most users together.
const
constaudiences:string[][]
audiences= [
['ada', 'grace', 'alan'],
['grace', 'alan'],
['edsger', 'barbara'],
['ada', 'edsger'],
]
const
constreached:Set<string>
reached=new
var Set:SetConstructor
new <string>(iterable?:Iterable<string> |null|undefined) =>Set<string> (+1 overload)
Returns the elements of an array that meet the condition specified in a callback function.
@param ― predicate A function that accepts up to three arguments. The filter method calls the predicate function one time for each element in the array.
@param ― thisArg An object to which the this keyword can refer in the predicate function. If thisArg is omitted, undefined is used as the this value.
filter((
user: string
user) =>!
constreached:Set<string>
reached.
Set<string>.has(value: string): boolean
@returns ― a boolean indicating whether an element with the specified value exists in the Set or not.
has(
user: string
user)).
Array<string>.length: number
Gets or sets the length of the array. This is a number one higher than the highest index in the array.
length
interface
interfaceCandidate
Candidate {
readonly
Candidate.index: number
index:number
/** The gain when last computed: an upper bound, because gains only shrink as the set grows. */
readonly
Candidate.gain: number
The gain when last computed: an upper bound, because gains only shrink as the set grows.
NaN is totally ordered as greater than every other number and equal
only to itself; 0 equals -0. Making the order total, rather than
returning 0 for every NaN comparison the way </> do, is what lets
heaps containing NaN keep a coherent invariant: with the partial rule,
NaN would compare equal to both 1 and 3 while 1 < 3, and a sift
could strand a smaller number behind it. NaN therefore drains last
from a min heap and first from a max heap.
Under this order -Infinity is the least element and NaN the greatest,
so the full chain reads -Infinity < -0 = 0 < 1 < Infinity < NaN.
numberOrder, (
candidate: Candidate
candidate:
interfaceCandidate
Candidate) =>
candidate: Candidate
candidate.
Candidate.gain: number
The gain when last computed: an upper bound, because gains only shrink as the set grows.
gain)
const
constfrontier:BinaryHeap<{
index:number;
gain:number;
}>
frontier=
maxBinaryHeap<{
index:number;
gain:number;
}>(order:Order<{
index:number;
gain:number;
}>, items?:Iterable<{
index:number;
gain:number;
}> |undefined):BinaryHeap<{
index:number;
gain:number;
}>
Create a max binary heap: the largest element per order is at the root,
and pop extracts in descending order.
Calls a defined callback function on each element of an array, and returns an array that contains the results.
@param ― callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array.
@param ― thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.
map((
_: string[]
_,
index: number
index) => ({
index: number
index,
gain: number
gain:
constgainOf: (index:number) =>number
gainOf(
index: number
index) })),
)
const
constpicks:number[]
picks:number[] = []
while (
constpicks:number[]
picks.
Array<T>.length: number
Gets or sets the length of the array. This is a number one higher than the highest index in the array.
replaceRoot installs the updated candidate with a single sift down. mapInputOrder tells the heap to compare
candidates by their cached gain.
Stochastic greedy instead draws a uniform sample of candidates per step, which is where knotkit/sampling and an
injected knotkit/prng source enter: the sample is reproducible from the seed, so a reported result is replayable.
problems/budget-allocation
measures all three against the exact optimum on a DR-submodular lattice objective — spreading r units of budget across
advertising channels to maximize expected reach:
At budget 75 on the low-overlap instance, lazy greedy needs 576 gain evaluations against full-scan greedy’s
22,500, and takes 0.267 ms against 4.274 ms.
At 16 units, lazy greedy matches the certified optimum at every budget, and takes 27.2 µs where branch and bound
takes 733 ms to certify that optimum.
Those are the repository’s numbers for one fixture on one machine. The address is the problem README’s
Benchmarks section; the
figure is
reach-and-time.png.
The same workload found the limit of the structure: the heap holds one entry per channel, so heap arity and graph
layout barely matter there. A lazy heap pays off when the pool is large — one cached bound per candidate — not when
the number of candidates is small enough that a scan is free.
Quality on the left, cost on the right. Lazy greedy pays nothing for skipping evaluations; stochastic greedy trades
at most 3.69% of reach for a bounded sample per step.