LeetCode 956. The highest billboard (DP)

Article Directory

1. Title

You are installing a billboard and want it to have the highest height.
This billboard will have two steel brackets, one on each side. The height of each steel support must be equal .

You have a bunch of steel rods that can be welded together.
For example, if the lengths of the steel bars are 1, 2 and 3, they can be welded together to form a 6-length bracket.

Returns the maximum possible installation height of the billboard . If the billboard cannot be installed, please return 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。
 
提示:
0 <= rods.length <= 20
1 <= rods[i] <= 1000
钢筋的长度总和最多为 5000

Source: LeetCode (LeetCode) Link: https://leetcode-cn.com/problems/tallest-billboard
Copyright is owned by LeetCode . For commercial reprints, please contact the official authorization. For non-commercial reprints, please indicate the source.

2. Problem solving

  • dp[i][j] Indicates the maximum height that can be formed when the i steel bar is processed and the gap between the two sides is j
class Solution {
    
    
public:
    int tallestBillboard(vector<int>& rods) {
    
    
        if(rods.size() <= 1)
            return 0;
        int dp[20][5001], n = rods.size();
        int total = accumulate(rods.begin(), rods.end(), 0);
        // dp[i][j] 表示处理完 i 支架,两边差距为 j 时,可以组成的最大高度
        memset(dp, -1, sizeof(dp));
        dp[0][rods[0]] = dp[0][0] = 0;
        for(int i = 1; i < rods.size(); i++) 
        {
    
       //样本维度
            for(int j = 0; j <= total; ++j)
            {
    
    
                if(dp[i-1][j] == -1)//上一行状态不存在
                    continue;
                // 当前钢筋不要,丢弃
                dp[i][j] = max(dp[i][j], dp[i-1][j]);
                // 当前钢筋,加在长的一边
                dp[i][j+rods[i]] = max(dp[i][j+rods[i]], dp[i-1][j]);
                // 当前钢筋,加在短的一边,现在高度差为 abs(j-rods[i])
                dp[i][abs(j-rods[i])] = max(dp[i][abs(j-rods[i])], dp[i-1][j]+min(j, rods[i]));
            }
        }
        // 返回高度差为 0 的情况
        return dp[n-1][0]==-1 ? 0 : dp[n-1][0];
    }
};

40 ms 8.1 MB


My CSDN blog address https://michael.blog.csdn.net/

Long press or scan the code to follow my official account (Michael Amin), cheer together, learn and progress together!
Michael Amin

Guess you like

Origin blog.csdn.net/qq_21201267/article/details/109004965
Recommended