Embercode
✕
Segment TreesQuick quiz

Node merging

6 questions. Covers Maximum subarray with node merging in Python.

Questions 1 to 5 of 6

  1. 1. Predict the output of this program. ``python from dataclasses import dataclass @dataclass(frozen=True) class Info: total: int prefix: int suffix: int best: int def leaf(value): return Info(value, value, value, value) def merge(left, right): if left is None: return right if right is None: return left total = left.total + right.total prefix = max(left.prefix, left.total + right.prefix) suffix = max(right.suffix, right.total + left.suffix) best = max(left.best, right.best, left.suffix + right.prefix) return Info(total, prefix, suffix, best) x = merge(leaf(-4), leaf(5)) y = merge(x, leaf(-2)) print(y) a = merge(leaf(-3), leaf(-1)) print(a.best) print(merge(None, a) is a) print(a.total, a.prefix, a.suffix) ``
  2. 2. Predict the output of this program. ``python from dataclasses import dataclass @dataclass(frozen=True) class Info: total: int prefix: int suffix: int best: int def leaf(value): return Info(value, value, value, value) def merge(left, right): if left is None: return right if right is None: return left total = left.total + right.total prefix = max(left.prefix, left.total + right.prefix) suffix = max(right.suffix, right.total + left.suffix) best = max(left.best, right.best, left.suffix + right.prefix) return Info(total, prefix, suffix, best) a = merge(leaf(2), leaf(-5)) b = merge(a, leaf(4)) print(a) print(b.best, b.prefix) ``
  3. 3. In the merge of a left child L and a right child R, which expression gives the prefix of the parent?
  4. 4. Which expression gives the best run that crosses the middle of a parent node?
  5. 5. Read this claim: a leaf sets best to max(0, value), which is correct because an empty run is always allowed. Is the claim true or false, and why?

5 question(s) left on this page.