leetcode.1626 无矛盾的最佳球队 - 最长上升子序列dp变种题

1626. 无矛盾的最佳球队

题目:

球队中的矛盾会限制球员的发挥,所以必须选出一支 没有矛盾 的球队。

如果一名年龄较小球员的分数 严格大于 一名年龄较大的球员,则存在矛盾。

同龄球员之间不会发生矛盾。

给你两个列表 scores 和 ages,其中每组 scores[i] 和 ages[i] 表示第 i 名球员的分数和年龄。请你返回 所有可能的无矛盾球队中得分最高那支的分数 。

思路:

按年龄大小进行从小到大排序

题目即是求排好序 找最长成绩上升子序列 求和

比如样例:

scores = [1,2,3,5], ages = [8,9,10,1]

按年龄排好序后

age [1,8,9,10]

sco [ 5,1,2,3]

定义f[i]为排序后以第i个球员为结尾的最大得分

class Solution {
    public int bestTeamScore(int[] scores, int[] ages) {
        int n=scores.length,res=0;
        int[] f=new int[n+1]; //定义f[i]是排序后以第i个球员为结尾的最大得分(最长上升子序列)
        int[][] a=new int[n][2]; 
        for(int i=0;i<n;i++) a[i]=new int[]{ages[i],scores[i]};
        Arrays.sort(a,(o1,o2)->o1[0]==o2[0]?o1[1]-o2[1]:o1[0]-o2[0]); //按年龄从小到大排
        
        for(int i=0;i<n;i++)
        {
            f[i]=a[i][1]; //如果i之前只有一个自己
            for(int j=0;j<i;j++)
                if(a[i][1]>=a[j][1]) 
                    f[i]=Math.max(f[i],f[j]+a[i][1]);
            
            res=Math.max(res,f[i]);
        }
        return res;
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_61639349/article/details/129715788