leetcode 956

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 rods which 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: [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:

  1. 0 <= rods.length <= 20
  2. 1 <= rods[i] <= 1000
  3. The sum of rods is at most 5000.
class Solution {
public:
    int tallestBillboard(vector<int>& rods)
    {
        int len = rods.size();
        int sum = accumulate(rods.begin(),rods.end(),0);
        vector<vector<int> > dp(len+1,vector<int>(sum+1,-1));
        dp[0][0] = 0;
        for(int i=1;i<=len;i++)
        {
            int h = rods[i-1];
            for(int j = 0;j<=sum-h;j++)
            {
                if(dp[i-1][j]<0) continue;
                dp[i][j] = max(dp[i][j],dp[i-1][j]);
                dp[i][j+h] = max(dp[i][j+h],dp[i-1][j]);
                dp[i][abs(j-h)] = max(dp[i][abs(j-h)],dp[i-1][j]+min(j,h));
            }
        }
        return dp[len][0];
    }
};

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值