- Notifications
You must be signed in to change notification settings - Fork 4
/
Copy path0956-tallest-billboard.rb
67 lines (54 loc) · 1.8 KB
/
0956-tallest-billboard.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# frozen_string_literal: true
# 956. Tallest Billboard
# Hard
# https://leetcode.com/problems/tallest-billboard/
=begin
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
=end
# @param {Integer[]} rods
# @return {Integer}
deftallest_billboard(rods)
max_sum=rods.sum / 2
dp={0=>0}
dp.default=0
rods.eachdo |rod|
cur={}
cur.default=0
dp.keys.eachdo |key|
cur[key + rod]=[dp[key] + rod,cur[key + rod]].maxunlesskey + rod > max_sum
cur[key]=[dp[key],cur[key]].max
cur[key - rod]=[dp[key],cur[key - rod]].maxunlesskey - rod < -max_sum
end
dp=cur
end
dp[0]
end
# **************** #
# TEST #
# **************** #
require"test/unit"
classTest_tallest_billboard < Test::Unit::TestCase
deftest_
assert_equal6,tallest_billboard([1,2,3,6])
assert_equal10,tallest_billboard([1,2,3,4,5,6])
assert_equal0,tallest_billboard([1,2])
end
end