LeetCode 0956. Tallest Billboard Solution in Java, C++, Python & More | Explanation + Code

CoderIndeed
0
0956. Tallest Billboard

Description

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

You are given a collection of rods that can be welded together. For example, if you have rods of lengths 1, 2, and 3, you can weld them together to make a support of length 6.

Return the largest possible height of your billboard installation. If you cannot support the billboard, return 0.

 

Example 1:

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.

Example 2:

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

Example 3:

Input: rods = [1,2]
Output: 0
Explanation: The billboard cannot be supported, so we return 0.

 

Constraints:

  • 1 <= rods.length <= 20
  • 1 <= rods[i] <= 1000
  • sum(rods[i]) <= 5000

Solutions

Solution 1

PythonJavaC++GoTypeScript
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)(code-box)

Solution 2

PythonJavaC++Go
class Solution: def tallestBillboard(self, rods: List[int]) -> int: n = len(rods) s = sum(rods) f = [[-inf] * (s + 1) for _ in range(n + 1)] f[0][0] = 0 t = 0 for i, x in enumerate(rods, 1): t += x for j in range(t + 1): f[i][j] = f[i - 1][j] if j >= x: f[i][j] = max(f[i][j], f[i - 1][j - x]) if j + x <= t: f[i][j] = max(f[i][j], f[i - 1][j + x] + x) if j < x: f[i][j] = max(f[i][j], f[i - 1][x - j] + x - j) return f[n][0](code-box)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !