HardNo. 0956

Tallest Billboard — LeetCode 956 Python Solution

Topics
Array, Dynamic Programming
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

PythonSolution
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

Time
O(n·m) (typical)
Space · auxiliary
O(n·m)or optimized

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

Related problems
No.ProblemDifficulty
0960Delete Columns to Make Sorted IIIHard
0045Jump Game IIMedium
0053Maximum SubarrayMedium
0055Jump GameMedium
0063Unique Paths IIMedium
0064Minimum Path SumMedium

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.

Free to download. Check it runs on your machine, then pick a plan.