美文网首页
2018-08-12 字节跳动笔试

2018-08-12 字节跳动笔试

作者: 菜鸡学算法 | 来源:发表于2018-08-12 21:37 被阅读0次

方法一:j,k表示两个人的分数,dp[j][k]表示团队积分

static void helper(int[][]score,int n,int total){
        int[][] dp=new int[total+1][total+1];
        for (int i = 0; i < dp.length; i++) {
            Arrays.fill(dp[i], Integer.MIN_VALUE);
        }
        dp[0][0]=0;
        for (int i = 0; i < n; i++) {
            for (int j = total; j >= 0; j--) {
                for (int k = total; k >= 0; k--) {
                    int t=Integer.MIN_VALUE;
                    if(j>=score[i][0]&&dp[j-score[i][0]][k]!=Integer.MIN_VALUE)t=Math.max(t, dp[j-score[i][0]][k]);
                    if(k>=score[i][0]&&dp[j][k-score[i][0]]!=Integer.MIN_VALUE)t=Math.max(t, dp[j][k-score[i][0]]);
                    if(t!=Integer.MIN_VALUE) {
                        t+=score[i][1];
                        dp[j][k]=Math.max(dp[j][k], t);
                    }
                }
            }
        }
        int max=0;
        for (int i = 0; i < dp.length; i++) {
            max=Math.max(max, dp[i][i]);
        }
        System.out.println(max);
        
    }

方法二:dp[i][j+total]表示到第i张牌时的团队积分,j为个人积分差值,因为j可能为负,所以要加偏移量,最后dp[n][total]就是到第n张牌且满足个人积分相等的团队积分

static void helper(int[][]score,int n,int total){
        int[][] dp=new int[n+1][total*2+1];
        for (int i = 0; i < dp.length; i++) {
            Arrays.fill(dp[i], Integer.MIN_VALUE);
        }
        dp[0][total]=0;
        for (int i = 1; i <= n; i++) {
            for (int j = total; j >=0 ; j--) {
                int temp=Integer.MIN_VALUE;
                if((j-score[i-1][0]>=0)&&dp[i-1][j-score[i-1][0]+total]!=Integer.MIN_VALUE) {
                    temp=Math.max(temp, dp[i-1][j-score[i-1][0]+total]);
                }
                    
                if((j+score[i-1][0]<=total)&&dp[i-1][j+score[i-1][0]+total]!=Integer.MIN_VALUE) {
                    temp=Math.max(temp, dp[i-1][j+score[i-1][0]+total]);
                }
                if(temp!=Integer.MIN_VALUE) {
                    temp+=score[i-1][1];
                    dp[i][j+total]=Math.max(temp , dp[i-1][j+total]);
                }
                
                System.out.println(dp[i][total]);
            }
            
        }
        System.out.println(dp[n][total]);
    }

相关文章

网友评论

      本文标题:2018-08-12 字节跳动笔试

      本文链接:https://www.haomeiwen.com/subject/tojebftx.html