Algorithm


Problem Name: 956. Tallest Billboard

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

Code Examples

#1 Code Example with Javascript Programming

Code - Javascript Programming


const tallestBillboard = function(rods) {
  const dp = {0 : 0}
  for(let el of rods) {
    for(let [diff, y] of Object.entries(dp)) {
      diff = +diff
      dp[diff + el] = Math.max(dp[diff + el] || 0, y)
      if(diff >= el) dp[diff - el] = Math.max(dp[diff - el] || 0, y + el)
      else dp[el - diff] = Math.max(dp[el - diff] || 0, y + diff)
    }
  }
  return dp['0']
};
Copy The Code & Try With Live Editor

Input

x
+
cmd
rods = [1,2,3,6]

Output

x
+
cmd
6

#2 Code Example with Python Programming

Code - Python Programming


class Solution:
    def tallestBillboard(self, rods):
        dp = {0: 0}
        for x in rods:
            for d, h in list(dp.items()):
                dp[d + x] = max(dp.get(x + d, 0), h)
                dp[abs(d - x)] = max(dp.get(abs(d - x), 0), h + min(d, x))
        return dp[0]         
Copy The Code & Try With Live Editor

Input

x
+
cmd
rods = [1,2,3,6]

Output

x
+
cmd
6
Advertisements

Demonstration


Previous
#955 Leetcode Delete Columns to Make Sorted II Solution in C, C++, Java, JavaScript, Python, C# Leetcode
Next
#957 Leetcode Prison Cells After N Days Solution in C, C++, Java, JavaScript, Python, C# Leetcode