10. Tallest Billboard (Difference State DP)

Difficulty:HardPattern:Difference State Dynamic ProgrammingTime:O(N * S)Space:O(S)

You are installing a billboard and want it to have the largest possible height. You have a collection of rods that can be welded together. Return the maximum possible height of your billboard installation.

How It Works & Algorithmic Design

Solves using Height Difference Dynamic Programming:

  1. DP Map State: Let dp[diff] be maximum shorter stand height achievable with height difference diff between left and right stands.
  2. Initialize: dp = { 0: 0 }.
  3. Rod Addition (For each rod $x$):
    • Copy current state map.
    • For each (diff, height) in current DP state:
      • Add to Taller Stand: newDiff = diff + x, updated height stays height.
      • Add to Shorter Stand: newDiff = |diff - x|, updated height becomes height + min(diff, x).
  4. Return: dp[0] (max height when left and right stands are equal).

Why This Approach Works Best

Keying states by height difference $\Delta$ compresses search complexity to $O(N \cdot S)$ time.

Example Walkthrough

Input

rods = [1, 2, 3, 6]

Available rod lengths.

Matched Stands

Left stand [1, 2, 3] = 6; Right stand [6] = 6.

Equal height stand pairs.

Output

6

Max billboard height.

Answer: Tallest Billboard implementation

function tallestBillboard(rods) {
  let dp = new Map([[0, 0]]);
  for (const x of rods) {
    const copy = new Map(dp);
    for (const [diff, height] of copy) {
      // Option 1: Add to taller stand
      dp.set(diff + x, Math.max(dp.get(diff + x) || 0, height));
      // Option 2: Add to shorter stand
      const newDiff = Math.abs(diff - x);
      const newHeight = height + Math.min(diff, x);
      dp.set(newDiff, Math.max(dp.get(newDiff) || 0, newHeight));
    }
  }
  return dp.get(0) || 0;
}

Maintain dynamic programming map tracking maximum stand height keyed by stand difference.

Key Takeaways
  • Keys dynamic state map by stand height difference $\Delta$.

  • Value stores maximum shorter stand height.

  • Final result is dp[0] where height difference is 0.