在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★ 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 have a collection of Return the largest possible height of your billboard installation. If you cannot support the billboard, return 0. Example 1: Input: [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: [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: [1,2]
Output: 0
Explanation: The billboard cannot be supported, so we return 0.
Note:
你正在安装一个广告牌,并希望它高度最大。这块广告牌将有两个钢制支架,两边各一个。每个钢支架的高度必须相等。 你有一堆可以焊接在一起的钢筋 返回广告牌的最大可能安装高度。如果没法安装广告牌,请返回 0。 示例 1: 输入:[1,2,3,6] 输出:6 解释:我们有两个不相交的子集 {1,2,3} 和 {6},它们具有相同的和 sum = 6。 示例 2: 输入:[1,2,3,4,5,6] 输出:10 解释:我们有两个不相交的子集 {2,3,5} 和 {4,6},它们具有相同的和 sum = 10。 示例 3: 输入:[1,2] 输出:0 解释:没法安装广告牌,所以返回 0。 提示:
1392ms 1 class Solution { 2 func tallestBillboard(_ rods: [Int]) -> Int { 3 var n:Int = rods.count 4 var h:Int = n/2 5 var o:Int = 10002 6 var ls:[Int] = [Int](repeating:-99999999,count:20005) 7 for i in 0..<Int(pow(3, Double(h))) 8 { 9 var s:Int = 0 10 var ass:Int = 0 11 var v:Int = i 12 for j in 0..<h 13 { 14 var w:Int = v % 3 15 if w == 1 16 { 17 18 } 19 else if w == 0 20 { 21 s += rods[j] 22 ass += rods[j] 23 } 24 else 25 { 26 s -= rods[j] 27 ass += rods[j] 28 } 29 v /= 3 30 } 31 ls[s+o] = max(ls[s+o], ass) 32 } 33 var ret:Int = 0 34 for i in 0..<Int(pow(3, Double(n - h))) 35 { 36 var s:Int = 0 37 var ass:Int = 0 38 var v:Int = i 39 for j in 0..<(n - h) 40 { 41 var w:Int = v % 3 42 if w == 1 43 { 44 45 } 46 else if w == 0 47 { 48 s += rods[j + h] 49 ass += rods[j + h] 50 } 51 else 52 { 53 s -= rods[j + h] 54 ass += rods[j + h] 55 } 56 v /= 3 57 } 58 ret = max(ret, (ls[o-s] + ass) / 2) 59 } 60 return ret 61 } 62 } 1480ms 1 class Solution { 2 struct State: Hashable { 3 let delta: Int 4 let score: Int 5 } 6 7 func make(from half: ArraySlice<Int>) -> [Int : Int] { 8 var states = Set<State>([.init(delta: 0, score: 0)]) 9 for i in half { 10 let x = Set(states.map { State(delta: $0.delta + i, score: $0.score) }) 11 let y = Set(states.map { State(delta: $0.delta, score: $0.score + i) }) 12 states = states.union(x.union(y)) 13 } 14 15 var delta = [Int : Int]() 16 for state in states { 17 delta[state.delta - state.score] = max(delta[state.delta - state.score] ?? 0, state.delta) 18 } 19 20 return delta 21 } 22 23 func tallestBillboard(_ rods: [Int]) -> Int { 24 let count = rods.count 25 let leftDelta = make(from: rods[..<(count / 2)]) 26 let rightDelta = make(from: rods[(count / 2)...]) 27 28 var answer = 0 29 30 for delta in leftDelta.keys { 31 if rightDelta.keys.contains(-delta) { 32 answer = max(answer, leftDelta[delta]! + rightDelta[-delta]!) 33 } 34 } 35 36 return answer 37 } 38 }
|
请发表评论