#956

Tallest Billboard

Hard
ArrayDynamic ProgrammingHash MapDynamic Programming
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n * sum(rods))
Space
O(1)
O(sum(rods))
💡

Intuition

Time O(n * sum(rods))Space O(sum(rods))

The optimal solution uses dynamic programming to keep track of the maximum height of the billboard that can be achieved with a given difference in height between the two sides. This reduces the number of combinations we need to check.

⚙️

Algorithm

3 steps
  1. 1Step 1: Initialize a DP array to store the maximum height for each possible height difference.
  2. 2Step 2: Iterate through each rod and update the DP array based on the current rod's height.
  3. 3Step 3: At the end, the maximum height for a difference of 0 will give the largest possible height.
solution.py9 lines
1def tallestBillboard(rods):
2    dp = {0: 0}
3    for rod in rods:
4        new_dp = dp.copy()
5        for diff, height in dp.items():
6            new_dp[diff + rod] = max(new_dp.get(diff + rod, 0), height)
7            new_dp[abs(diff - rod)] = max(new_dp.get(abs(diff - rod), 0), height + min(diff, rod))
8        dp = new_dp
9    return dp[0]

Complexity note: This complexity comes from iterating through each rod and updating the DP map based on the potential height differences, which can range up to the total sum of the rods.

  • 1The problem can be viewed as a subset-sum problem with constraints.
  • 2Dynamic programming helps in efficiently tracking possible height differences.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.