LeetCode 3177: Find the Maximum Length of a Good Subsequence II Solution
Master LeetCode problem 3177 (Find the Maximum Length of a Good Subsequence II), a hard challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
3177. Find the Maximum Length of a Good Subsequence II
Problem Explanation
Explanation:
To solve this problem, we can use dynamic programming. We will iterate over all possible subsequences of the input array nums, keeping track of the maximum length of a good subsequence we can form. At each step, we consider whether to include the current element in the subsequence or not, based on the number of occurrences of the element so far.
We will maintain a 3-dimensional dynamic programming array dp[i][j][l] where i represents the index in nums, j represents the number of different elements added so far, and l represents the number of times the last element has been added.
The state transition is as follows:
- If we do not include the current element
nums[i]in the subsequence,dp[i][j][l] = max(dp[i][j][l], dp[i+1][j][l]). - If we include the current element
nums[i]in the subsequence,dp[i][j][l] = max(dp[i][j][l], dp[i+1][j+1][0] + 1). - We also update the state when the last element is repeated:
dp[i][j][l] = max(dp[i][j][l], dp[i+1][j][l+1] + 1).
The final answer will be the maximum value in dp[0][j][l] for all valid values of j and l.
:
Solution Code
class Solution {
public int maxGoodSubsequence(int[] nums, int k) {
int n = nums.length;
int[][][] dp = new int[n+1][k+1][n+1];
for (int i = n - 1; i >= 0; i--) {
for (int j = 0; j <= k; j++) {
for (int l = 0; l <= n; l++) {
dp[i][j][l] = Math.max(dp[i+1][j][l], dp[i+1][j+1][0] + 1);
if (l > 0) {
dp[i][j][l] = Math.max(dp[i][j][l], dp[i+1][j][l-1] + 1);
}
}
}
}
int maxLen = 0;
for (int j = 0; j <= k; j++) {
for (int l = 0; l <= n; l++) {
maxLen = Math.max(maxLen, dp[0][j][l]);
}
}
return maxLen;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 3177 (Find the Maximum Length of a Good Subsequence II)?
This page provides optimized solutions for LeetCode problem 3177 (Find the Maximum Length of a Good Subsequence II) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 3177 (Find the Maximum Length of a Good Subsequence II)?
The time complexity for LeetCode 3177 (Find the Maximum Length of a Good Subsequence II) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 3177 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 3177 in Java, C++, or Python.