3176. Find the Maximum Length of a Good Subsequence I

52 阅读1分钟

image.png

solution: dp O(N^2 * k),O(NK)

  • dp[i][j] represents the maximum length of subsequence ending at index i with j distinct elements.
  • Iterate over each element of nums starting from the second element (i = 1).
    • For each element, iterate over all indices before it (l < i).
    • If the current element at index i != the element at index l, it means a new distinct element is being added.
      • In this case, if j > 0, update dp[i][j] to dp[l][j-1] + 1 if it results in a longer subsequence.
    • If the current element at index i == the element at index x, no new distinct element is being added.
      • In this case, simply update dp[i][j] to dp[l][j] + 1 if it results in a longer subsequence.
    • Update max with the maximum length found so far.
class Solution {
    public int maximumLength(int[] nums, int k) {
        int[][] dp = new int[nums.length][k + 1];
        int res = 1;
        //  Set each element of dp[i] to 1, 
        // as each element itself forms a subsequence of length 1.
        for(int i = 0; i < nums.length; i++){
            Arrays.fill(dp[i], 1);
        }

        for (int i = 0; i < nums.length; i++) {
            for (int l = 0; l < i; l++) {
                for (int j = 0; j <= k; j++) {
                    if (nums[l] == nums[i]) {
                    // rolling, beacause we are interating elements before i
                        dp[i][j] = Math.max(dp[i][j], 1 + dp[l][j]);
                    } else if (j >= 1) {
                        dp[i][j] = Math.max(dp[i][j], 1 + dp[l][j - 1]);
                    }

                    res = Math.max(res, dp[i][j]);
                }
            }
        }
        return res;
    }
}