区间安排的一些问题(给左右边界)

每行有3个整数st、ed、val,分别表示项目的开始、截至时间和项目的报酬,相邻两数之间用空格隔开。
st、ed、value取值均在32位有符号整数(int)的范围内,输入数据保证所有数据的value总和也在int范围内。

求最大报酬

3
1 3 6
4 8 9
2 5 16
4
1 14 10
5 20 15
15 20 8
18 22 12
输出
16
22
先按照start排序,当前项目加入,与前面每一个项目比较,如果小于前面项目的end
static class point{
        int st;
        int ed;
        int value;
        public point(int st,int ed,int value) {
            this.st=st;
            this.ed=ed;
            this.value=value;
        }
    }
    public static void main(String[] args) {
        Scanner sc=new Scanner(System.in);
        int n=sc.nextInt();
        point[] points=new point[n];
        for(int i=0;i<n;i++) {
            points[i]=new point(sc.nextInt(),sc.nextInt(),sc.nextInt());
        }
        Arrays.sort(points,new Comparator<point>() {
            @Override
            public int compare(point o1, point o2) {
                // TODO Auto-generated method stub
                return o1.st-o2.st;
            }
        });
        int[] dp=new int[n];//dp[i],前i+1个任务所带来的最大薪酬
        for(int i=0;i<n;i++) dp[i]=points[i].value;
        for(int i=1;i<n;i++) {
            for(int j=i-1;j>=0;j--) {
                if(points[i].st>=points[j].ed)
                {
                    dp[i]=Math.max(dp[i], dp[j]+points[i].value);
                }
            }
            dp[i]=Math.max(dp[i], dp[i-1]);
        }
        System.out.println(dp[n-1]);
    }

和上面类似,这次我们求重叠的最大的value

3
1 3 6
4 8 9
2 5 16
4
1 14 10
5 20 15
15 20 8
18 22 12
输出
25
35
static class point{
        int st;
        int ed;
        int value;
        public point(int st,int ed,int value) {
            this.st=st;
            this.ed=ed;
            this.value=value;
        }
    }
    public static void main(String[] args) {
        Scanner sc=new Scanner(System.in);
        int n=sc.nextInt();
        point[] points=new point[n];
        for(int i=0;i<n;i++) {
            points[i]=new point(sc.nextInt(),sc.nextInt(),sc.nextInt());
        }
        Arrays.sort(points,new Comparator<point>() {
            @Override
            public int compare(point o1, point o2) {
                // TODO Auto-generated method stub
                return o1.st-o2.st;
            }
        });
        int[] dp=new int[n];//dp[i],前i+1个任务所带来的最大值
        for(int i=0;i<n;i++) dp[i]=points[i].value;
        int res=0;
        for(int i=1;i<n;i++) {
            for(int j=i-1;j>=0;j--) {
                if(points[i].st<points[j].ed)
                {
                    dp[i]=dp[i]+points[j].value;
                }
            }
            res=Math.max(res, dp[i]);
        }
        System.out.println(res);
    }

小红书面试官说还能优化??

posted @ 2019-09-11 10:47  LeeJuly  阅读(182)  评论(0)    收藏  举报