Skip to content

Monotone submodular maximization

Use a heap to make greedy selections with fewer gain evaluations, then compare the results with a full scan.

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.

Method Gain evaluations Guarantee Structure it needs
Full-scan greedy 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.

time O(nc + r(c + log n)), where r counts heap iterations after initialization · space O(n), one cached gain per candidate · c is the cost of one marginal-gain evaluation

Use maxBinaryHeap from knotkit/heap to keep the candidate with the highest upper bound at the root.

lazy-greedy.ts
import {
function mapInputOrder<A, B>(order: Order<A>, f: (b: B) => A): Order<B>

Derive an Order<B> from an Order<A> by mapping each B to an A with f before comparing.

@example

const byAge = mapInputOrder(numberOrder, (user: { age: number }) => user.age)

mapInputOrder
,
function maxBinaryHeap<A>(order: Order<A>, items?: Iterable<A>): BinaryHeap<A>

Create a max binary heap: the largest element per order is at the root, and pop extracts in descending order.

@example

const heap = maxBinaryHeap(numberOrder, [30, 1, 50, 20])
heap.peek() // 50

@param ― order - Total ordering over the elements.

@param ― items - Optional initial elements, in iteration order.

maxBinaryHeap
,
const numberOrder: 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
const audiences: string[][]
audiences
= [
['ada', 'grace', 'alan'],
['grace', 'alan'],
['edsger', 'barbara'],
['ada', 'edsger'],
]
const
const reached: Set<string>
reached
= new
var Set: SetConstructor
new <string>(iterable?: Iterable<string> | null | undefined) => Set<string> (+1 overload)
Set
<string>()
const
const gainOf: (index: number) => number
gainOf
= (
index: number
index
: number): number => (
const audiences: string[][]
audiences
[
index: number
index
] ?? []).
Array<string>.filter(predicate: (value: string, index: number, array: string[]) => unknown, thisArg?: any): 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
) => !
const reached: 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
interface Candidate
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.

gain
: number
}
const
const byGain: Order<Candidate>
byGain
=
mapInputOrder<number, Candidate>(order: Order<number>, f: (b: Candidate) => number): Order<Candidate>

Derive an Order<B> from an Order<A> by mapping each B to an A with f before comparing.

@example

const byAge = mapInputOrder(numberOrder, (user: { age: number }) => user.age)

mapInputOrder
(
const numberOrder: 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
, (
candidate: Candidate
candidate
:
interface Candidate
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
const frontier: 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.

@example

const heap = maxBinaryHeap(numberOrder, [30, 1, 50, 20])
heap.peek() // 50

@param ― order - Total ordering over the elements.

@param ― items - Optional initial elements, in iteration order.

maxBinaryHeap
(
const byGain: Order<Candidate>
byGain
,
const audiences: string[][]
audiences
.
Array<string[]>.map<{
index: number;
gain: number;
}>(callbackfn: (value: string[], index: number, array: string[][]) => {
index: number;
gain: number;
}, thisArg?: any): {
index: number;
gain: number;
}[]

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
:
const gainOf: (index: number) => number
gainOf
(
index: number
index
) })),
)
const
const picks: number[]
picks
: number[] = []
while (
const picks: 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.

length
< 2) {
const
const top: {
index: number;
gain: number;
}
top
=
const frontier: BinaryHeap<{
index: number;
gain: number;
}>
frontier
.
BinaryHeap<{ index: number; gain: number; }>.peek: () => {
index: number;
gain: number;
}

Return the extreme element without removing it. O(1).

Property syntax for the same variance reason as

push

.

@throws ― {HeapInvalidInputError} With code EMPTY when the heap is empty.

peek
()
const
const fresh: number
fresh
=
const gainOf: (index: number) => number
gainOf
(
const top: {
index: number;
gain: number;
}
top
.
index: number
index
)
if (
const fresh: number
fresh
<
const top: {
index: number;
gain: number;
}
top
.
gain: number
gain
) {
const frontier: BinaryHeap<{
index: number;
gain: number;
}>
frontier
.
BinaryHeap<{ index: number; gain: number; }>.replaceRoot: (value: {
index: number;
gain: number;
}) => {
index: number;
gain: number;
}

Return the current root and replace it with the supplied value, preserving size. O(log n).

@throws ― {HeapInvalidInputError} With code EMPTY when the heap is empty.

replaceRoot
({ ...
const top: {
index: number;
gain: number;
}
top
,
gain: number
gain
:
const fresh: number
fresh
}) // stale bound: lower it and look again
continue
}
const frontier: BinaryHeap<{
index: number;
gain: number;
}>
frontier
.
BinaryHeap<{ index: number; gain: number; }>.pop: () => {
index: number;
gain: number;
}

Remove and return the extreme element — the minimum for min kinds, the maximum for max kinds, under the factory order. O(log n).

Property syntax for the same variance reason as

push

.

@throws ― {HeapInvalidInputError} With code EMPTY when the heap is empty.

pop
()
const picks: number[]
picks
.
Array<number>.push(...items: number[]): number

Appends new elements to the end of an array, and returns the new length of the array.

@param ― items New elements to add to the array.

push
(
const top: {
index: number;
gain: number;
}
top
.
index: number
index
)
for (const
const user: string
user
of
const audiences: string[][]
audiences
[
const top: {
index: number;
gain: number;
}
top
.
index: number
index
] ?? []) {
const reached: Set<string>
reached
.
Set<string>.add(value: string): Set<string>

Appends a new element with a specified value to the end of the Set.

add
(
const user: string
user
)
}
}
const picks: number[]
picks
// [0, 2]
const reached: Set<string>
reached
.
Set<string>.size: number

@returns ― the number of (unique) elements in Set.

size
// 5

The same snippet runs, with every stated result checked, on the guide Pick the k items that cover the most.

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.

Left: reach below the certified best at each even budget. Lazy greedy is 0% short at every budget; stochastic greedy is at most 3.69% short, at 6 units. Right: at 16 units, lazy greedy takes 27.2 microseconds, while branch and bound takes 733 milliseconds to certify the optimum.

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.