- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Tallest Billboard in C++
Suppose we are installing a billboard and we want it to have the largest height. The billboard will have two steel supports on both sides. Each support must be of equal height. We also have a collection of rods which can be welded together. So, if we have rods of lengths 1, 2, and 3, we can weld them together to make a support of length 6. We have to find the largest possible height of our billboard installation. If we cannot support the billboard, return 0.
So, if the input is like [1,2,2,3,3,3,4], then the output will be 9, as we have subsets like [1,2,2,4] and [3,3,3].
To solve this, we will follow these steps −
sum := 0, n := size of rods, N := 2 * 5000
Define one 2D array dp(n + 1) x (N + 1, -1)
dp[0, 5000] := 0
for initialize i := 0, when i < n, update (increase i by 1), do −
for initialize j := 0, when j <= N, update (increase j by 1), do −
x := rods[i]
if j - x >= 0 and dp[i, j - x] is not equal to -1, then −
dp[i + 1, j] = max of dp[i + 1, j] and dp[i, j - x] + x
if j + x <= N and dp[i, j + x] is not equal to -1, then −
dp[i + 1, j] = max of dp[i + 1, j] and dp[i, j + x]
if dp[i, j] is not equal to -1, then
dp[i + 1, j] = max of dp[i, j] and dp[i + 1, j]
return dp[n, 5000]
Let us see the following implementation to get better understanding −
Example
#include <bits/stdc++.h> using namespace std; class Solution { public: int tallestBillboard(vector<int>& rods){ int sum = 0; int n = rods.size(); int N = 2 * 5000; vector<vector<int> > dp(n + 1, vector<int>(N + 1, -1)); dp[0][5000] = 0; for (int i = 0; i < n; i++) { for (int j = 0; j <= N; j++) { int x = rods[i]; if (j - x >= 0 && dp[i][j - x] != -1) { dp[i + 1][j] = max(dp[i + 1][j], dp[i][j - x] + x); } if (j + x <= N && dp[i][j + x] != -1) { dp[i + 1][j] = max(dp[i + 1][j], dp[i][j + x]); } if (dp[i][j] != -1) { dp[i + 1][j] = max(dp[i][j], dp[i + 1][j]); } } } return dp[n][5000]; } }; main(){ Solution ob; vector<int> v = {1,2,2,3,3,3,4}; cout << (ob.tallestBillboard(v)); }
Input
{1,2,2,3,3,3,4}
Output
9