#3202

Find the Maximum Length of Valid Subsequence II

Medium
ArrayDynamic ProgrammingDynamic ProgrammingArray
LeetCode ↗

Approaches

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

Intuition

Time O(n)Space O(k)

The optimal approach uses dynamic programming to store the maximum length of valid subsequences based on the remainder when the last element is divided by k. This reduces the problem size significantly.

⚙️

Algorithm

3 steps
  1. 1Step 1: Initialize a dp array of size k to store the maximum length of subsequences for each possible remainder.
  2. 2Step 2: Iterate through each number in nums and update the dp array based on the current number's contribution to valid subsequences.
  3. 3Step 3: For each number, calculate its remainder and update the dp array accordingly.
solution.py12 lines
1# Full working Python code
2
3def maxLengthValidSubsequence(nums, k):
4    dp = [0] * k
5    for num in nums:
6        rem = num % k
7        new_dp = dp[:]
8        for i in range(k):
9            if (i + rem) % k == (rem + rem) % k:
10                new_dp[(i + rem) % k] = max(new_dp[(i + rem) % k], dp[i] + 1)
11        dp = new_dp
12    return max(dp)

Complexity note: The time complexity is O(n) because we iterate through the array once, and the space complexity is O(k) due to the dp array.

  • 1The validity condition relies on the remainders when divided by k, which allows us to group numbers effectively.
  • 2Dynamic programming can significantly reduce the complexity by storing intermediate results.

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