10. Tallest Billboard (Difference State DP)
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:
- DP Map State: Let
dp[diff]be maximum shorter stand height achievable with height differencediffbetween left and right stands. - Initialize:
dp = { 0: 0 }. - 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 staysheight. - Add to Shorter Stand:
newDiff = |diff - x|, updated height becomesheight + min(diff, x).
- Add to Taller Stand:
- 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
rods = [1, 2, 3, 6]
Available rod lengths.
Left stand [1, 2, 3] = 6; Right stand [6] = 6.
Equal height stand pairs.
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.
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.