#3176
Find the Maximum Length of a Good Subsequence I
MediumArrayHash TableDynamic ProgrammingHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n log n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n log n)Space O(n)
The optimal solution uses dynamic programming to efficiently calculate the maximum length of a good subsequence by leveraging the properties of the subsequences and counting differences in a structured way.
⚙️
Algorithm
3 steps- 1Step 1: Create a frequency map to count occurrences of each number in nums.
- 2Step 2: Sort the unique numbers and initialize a DP array to store maximum lengths.
- 3Step 3: Iterate through the unique numbers and update the DP array based on the allowed differences (k).
solution.py15 lines
1# Full working Python code
2from collections import Counter
3
4def max_good_subsequence(nums, k):
5 freq = Counter(nums)
6 unique_nums = list(freq.keys())
7 unique_nums.sort()
8 dp = [0] * (len(unique_nums) + 1)
9
10 for i in range(1, len(unique_nums) + 1):
11 dp[i] = dp[i - 1] + freq[unique_nums[i - 1]]
12 if i > k:
13 dp[i] -= freq[unique_nums[i - k - 1]]
14
15 return dp[len(unique_nums)]ℹ
Complexity note: The time complexity is O(n log n) due to sorting the unique elements, while the space complexity is O(n) for storing the frequency map and DP array.
- 1Understanding the constraints on differences is crucial for optimizing the solution.
- 2Using frequency maps can significantly reduce the complexity of counting occurrences.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.