π WAYPOINT LESSON
Max-Subarray Segment Tree Node
βββ advancedβ³ 35 min readπ Lesson 128 of 281
Each node keeps (total, prefix, suffix, best); pull() merges the child nodes and the cross-boundary case.
The max-subarray node
For a node covering a range store four values:
- total β sum of the whole range
- pre β best sum of a prefix
- suf β best sum of a suffix
- best β best sum of any subarray inside the range
pull (merge children L, R):
n.total = L.total + R.total
n.pre = max(L.pre, L.total + R.pre)
n.suf = max(R.suf, R.total + L.suf)
n.best = max(L.best, R.best, L.suf + R.pre)
L.suf + R.pre is the cross term β forgetting it degenerates to two
independent Kadanes and fails on diamonds like [5, -10, 6]. With lazy
ASSIGN, apply() sets all four from v and the length: total = vΒ·len,
pre = suf = best = max(v, vΒ·len) β careful with v > 0 (take the whole
range) vs v <= 0 (take one element... unless empty subarrays are allowed;
this course counts non-empty subarrays).
β‘ Now practice
Ready to CodeLazy Tree DrillsRange add/min, mixed assign/add compose order, bulk closed-form loads, and the max-subarray node with a cross-boundary discriminator.
4 challenges Β· Β· ~110 min