~/problems / Search tricks / Ternary search

Basics: peak of a unimodal function on reals

easy basics ~10 min

A function f is unimodal on [lo, hi] when it strictly increases up to a single peak and then strictly decreases (either side may be empty, so the peak can sit at lo or hi).

Write argmax(f, lo: float, hi: float) -> float that returns the x in [lo, hi] where f is largest, accurate to within 1e-6.

argmax(lambda x: -(x - 2.5) ** 2, 0.0, 10.0)   # about 2.5
argmax(lambda x: x, 0.0, 1.0)                  # about 1.0  (peak at the right edge)
argmax(math.sin, 0.0, math.pi)                 # about 1.5707963 (pi / 2)

Constraints: lo < hi, hi - lo <= 10^6. You may call f at most 500 times; the tests count.

Show hint

evaluate m1 = lo + (hi - lo) / 3 and m2 = hi - (hi - lo) / 3; if f(m1) < f(m2) the peak can't be in [lo, m1], so set lo = m1, otherwise set hi = m2, and repeat a fixed number of times (about 100).

Topic: Ternary search. Maximize a unimodal function; or binary search on the slope.

0:00
Ctrl ' run · Ctrl ↵ submit
esc