Tallest Billboard — LeetCode 956 Python Solution

HardArrayDynamic Programming
Problem
#956
Reading time
2 min

The problem

You are installing a billboard and want it to have the largest height. The billboard will have two steel supports, one on each side.

Example

Input
rods = [1,2,3,6]
Output
6
Explanation
We have two disjoint subsets {1,2,3} and {6}, which have the same sum = 6.

Python solution

Python
class Solution:
    def tallestBillboard(self, rods: List[int]) -> int:
        @cache
        def dfs(i: int, j: int) -> int:
            if i >= len(rods):
                return 0 if j == 0 else -inf
            ans = max(dfs(i + 1, j), dfs(i + 1, j + rods[i]))
            ans = max(ans, dfs(i + 1, abs(rods[i] - j)) + min(j, rods[i]))
            return ans

        return dfs(0, 0)

Complexity

MeasureComplexity
TimeO(n·m) (typical)
SpaceO(n·m) or optimized auxiliary

Pattern: Dynamic Programming

Define a state, write the transition, and stop recomputing the same subproblem. LeetCode 956. Tallest Billboard is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Dynamic Programming.

The dynamic programming guide has the Python template for the pattern and the 481 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 956. Tallest Billboard?
LeetCode 956. Tallest Billboard is rated Hard on LeetCode.
What topics does LeetCode 956. Tallest Billboard cover?
LeetCode 956. Tallest Billboard is tagged Array and Dynamic Programming on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview