956. Tallest Billboard
Đề Bài
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 <= 201 <= rods[i] <= 1000sum(rods[i]) <= 5000
Thuật Toán & Kỹ Thuật
⏱️ Thời gian
O(n)
💾 Không gian
O(n)
Lời Giải
C++
0956-tallest-billboard.cpp
class Solution {
private:
vector<int> rods;
public:
const int limit = 10000;
void dfs(int i, int n, int lSum, int rSum, unordered_map<int, int> &dp) {
if (i == n) {
int distance = lSum - rSum + (limit >> 1);
dp[distance] = max(dp[distance], lSum);
return;
}
dfs(i + 1, n, lSum + rods[i], rSum, dp);
dfs(i + 1, n, lSum, rSum + rods[i], dp);
dfs(i + 1, n, lSum, rSum, dp);
}
int tallestBillboard(vector<int>& rods) {
unordered_map<int, int> lSubset, rSubset;
this->rods = rods;
int n = rods.size();
int mid = n >> 1;
dfs(0, mid, 0, 0, lSubset);
dfs(mid, n, 0, 0, rSubset);
int ans = 0;
for (auto [key, value] : lSubset) {
if (rSubset.count(limit - key)) {
ans = max(ans, lSubset[key] + rSubset[limit - key]);
}
}
return ans;
}
};