leetcode(956)最高的广告牌

最高的广告牌

解题思路:动态规划,自底向上,穷举法

class Solution {
    public int tallestBillboard(int[] rods) {
        int len = rods.length;
        int sum = 0;
        for(int i=0;i<len;i++){
           sum+=rods[i];
        }
        int[][] dp = new int[len+1][sum+1];
        for(int i=0;i<len+1;i++){
            for(int j=0;j<sum+1;j++){
                dp[i][j]=-1;
            }
        }
        sum=0;
        dp[0][0] = 0;
        for (int i = 1; i <= len; i++) {
            sum += i==1?0:rods[i-2];
            for (int j = 0; j <= sum; j++) {
                if(dp[i-1][j]==-1){
                    continue;
                }
                dp[i][j] = Math.max(dp[i-1][j],dp[i][j]);
                dp[i][j+rods[i-1]] = Math.max(dp[i-1][j], dp[i][j+rods[i-1]]);
                dp[i][Math.abs(j-rods[i-1])] = Math.max(dp[i][Math.abs(j-rods[i-1])], dp[i-1][j] + Math.min(j,rods[i-1]));
            }
        }
        return dp[len][0];
    }
}

 

posted @ 2019-07-03 11:14  海平面下的我们  阅读(596)  评论(0编辑  收藏  举报