progress

~/problems / 2-D dynamic programming / Interval (range) DP

Least wobbly hanging mobile

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or fight a boss.

medium ~25 min

An art student builds a hanging mobile from a row of ornaments weights. She repeatedly takes two neighbouring pieces (an ornament, or a part she already built) and hangs them from the ends of a new rod, which becomes one piece weighing their sum, until one rod holds everything. The row's order never changes.

A rod wobbles by abs(left - right). Implement min_wobble(weights: list[int]) -> int: the smallest possible total wobble.

min_wobble([1, 1, 2, 4])  # 0   (1|1) weighs 2, (2|2) weighs 4, (4|4): every rod balances
min_wobble([2, 2, 3, 1])  # 2   (2|2) and (3|1) both weigh 4, then (4|4): wobble 0 + 2 + 0

Joining the most balanced pair first does not work: on the second example it ends up at 7. A single ornament has wobble 0.

Up to 80 ornaments, weights up to 1000.

⭐ Bonus: a speed test with 80 ornaments earns a star in O(n³). Trying every way to build the mobile won't finish there.

Show hint

the top rod over weights[l..r] splits it into l..k and k+1..r and wobbles by the difference of their sums. So wobble[l][r] = min over k of wobble[l][k] + wobble[k+1][r] + abs(sum(l..k) - sum(k+1..r)); use prefix sums and fill by increasing length.

Topic: Interval (range) DP. dp[l][r] over subarrays, filled by increasing length; pick the split point.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc