#3177

Find the Maximum Length of a Good Subsequence II

Hard
ArrayHash TableDynamic ProgrammingHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal approach uses dynamic programming to efficiently calculate the maximum length of a good subsequence by tracking the counts of each unique number and how they can be combined while respecting the constraints of differing indices.

⚙️

Algorithm

4 steps
  1. 1Step 1: Count the frequency of each unique number in nums.
  2. 2Step 2: Store these frequencies in a list and sort it.
  3. 3Step 3: Use a dynamic programming table where dp[i][j] represents the maximum length of a good subsequence using the first i unique numbers with at most j differing indices.
  4. 4Step 4: Iterate through the unique numbers and update the dp table based on the frequency of the current number and the previous states.
solution.py19 lines
1# Full working Python code
2from collections import Counter
3
4def max_good_subsequence(nums, k):
5    count = Counter(nums)
6    freq = list(count.values())
7    n = len(freq)
8    dp = [[0] * (k + 1) for _ in range(n + 1)]
9
10    for i in range(1, n + 1):
11        for j in range(k + 1):
12            dp[i][j] = dp[i - 1][j] + freq[i - 1]  # take all of current number
13            if j > 0:
14                dp[i][j] = max(dp[i][j], dp[i - 1][j - 1] + freq[i - 1])  # take one less
15
16    return dp[n][k]
17
18# Example usage
19print(max_good_subsequence([1, 2, 1, 1, 3], 2))

Complexity note: The time complexity is O(n) because we only pass through the array a few times: once to count frequencies and once to fill the dynamic programming table. The space complexity is O(n) due to the storage of frequency counts and the DP table.

  • 1Understanding how to count unique elements and their frequencies is crucial for optimizing the solution.
  • 2Dynamic programming can effectively manage state transitions based on constraints, leading to efficient solutions.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.