368. Largest Divisible Subset

class Solution {
    public List<Integer> largestDivisibleSubset(int[] nums) {
        List<Integer> ans = new ArrayList<>();
        if (nums == null || nums.length == 0) return ans;

        Arrays.sort(nums);
        int max = 0, index = -1, n = nums.length;
        int[] dp = new int[n];
        int[] pre = new int[n];
        for (int i = 0; i < n; i++){
            dp[i] = 1;
            pre[i] = -1;
            for (int j = 0; j < i; j++){
                if (nums[i] % nums[j] == 0 && dp[j] + 1 > dp[i]){
                    dp[i] = dp[j] + 1;
                    pre[i] = j;
                }
            }
            if (dp[i] > max){
                max = dp[i];
                index = i;
            }
        }

        while (index != -1){
            ans.add(nums[index]);
            index = pre[index];
        }

        return ans;
    }
}

673 Number of Longest Increasing Subsequence

class Solution {
    public int findNumberOfLIS(int[] nums) {
        if (nums == null || nums.length == 0) return 0;
        int n = nums.length;
        // count[i]: how many LIS at nums[i]
        int[] count = new int[n];
        // length[i]: the longest length of LIS at nums[i]
        int[] length = new int[n];

        Arrays.fill(count, 1);

        for (int j = 0; j < n; j++){
            length[j] = 1;
            for (int i = 0; i < j; i++){
                if (nums[j] > nums[i]){
                    if (length[i] >= length[j]){
                        count[j] = count[i];
                        length[j] = length[i] + 1;
                    }
                    else if (length[i] + 1 == length[j]){
                        count[j] += count[i];
                    }
                }
            }
        }

        int max = 0;
        for (int i = 0; i < length.length; i++){
            max = Math.max(max, length[i]);
        }

        int ans = 0;
        for (int i = 0; i < count.length; i++){
            if (length[i] == max) ans += count[i];
        }

        System.out.println(Arrays.toString(length));
        System.out.println(Arrays.toString(count));

        return ans;
    }
}

674.Longest Continuous Increasing Subsequence

class Solution {
    public int findLengthOfLCIS(int[] nums) {
        if (nums == null || nums.length == 0) return 0;
        int[] dp = new int[nums.length];

        for (int i = 0; i < nums.length; i++){
            dp[i] = 1;
            if (i - 1 >= 0 && nums[i] > nums[i - 1]){
                dp[i] = dp[i - 1] + 1;
            }
            //System.out.println(Arrays.toString(dp));
        }

        int ans = 0;
        for (int i = 0; i < dp.length; i++){
            ans = Math.max(ans, dp[i]);
        }

        return ans;
    }
}

results matching ""

    No results matching ""