leetcode1235. 规划兼职工作(java)

2023-12-28 16:35:21

记忆化+递归+二分;

选或者不选,取最大值(之前二分一直有问题,经过指点,修改了一下)

class Solution {
    private int []memo;
    private int[][] nums;
    public int jobScheduling(int[] startTime, int[] endTime, int[] profit) {
        
        int [][]nums = new int[startTime.length][3];
        for (int i = 0; i < startTime.length; i++) {
            nums[i] = new int[]{startTime[i], endTime[i], profit[i]};
        }
        Arrays.sort(nums, Comparator.comparingInt(a -> a[1]));
         memo = new int[profit.length];
        return dfs(nums,startTime.length - 1);
    }
    public int dfs(int[][] nums,int i){
        if(i < 0){
            return 0;
        }
        if(memo[i] != 0){
            return memo[i];
        }
        int res = dfs(nums,i - 1);
        int j = search(nums,nums[i][0],i - 1);
        res = Math.max(res,dfs(nums,j) + nums[i][2]);
        memo[i] = res;
        return res;
    }

    public int search(int[][] nums, int startTime,int right) {
        int index = -1;
        int i = 0;
        int j = right;
        while(i <=j){
            int mid = (i + j + 1) >> 1;
            if(nums[mid][1] <= startTime){
                index = mid;
                i = mid + 1;
            }else{
                j = mid - 1;
            }
        }
        return index;
    }
}

文章来源:https://blog.csdn.net/qq_51680483/article/details/135247950
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。