Problem Description
Given an integer array nums and a positive integer k, find the length of the longest subsequence of nums that is “valid”. A subsequence sub (of length x) is valid if for every pair of consecutive elements in sub, the value of (sub[i] + sub[i+1]) % k is the same for every i from 0 to x-2.
Key Insights
- The “validity” of a subsequence is determined entirely by the constant modulo (r) derived from the sum of its first two elements.
- A single element subsequence is trivially valid (since there is no pair to impose a condition).
- When building a valid subsequence, once a modulo value r is established, every new element must satisfy (last_element + new_element) % k == r.
- We can employ dynamic programming by maintaining, for each index, possible chains ending there with a fixed modulo value r.
- For any two indices i and j (with i < j), a pair (nums[i], nums[j]) gives a potential starting chain with r = (nums[i] + nums[j]) % k. This chain can be extended if a later element satisfies the same pair condition.
Space and Time Complexity
Time Complexity: O(n²) – We iterate through pairs of indices. Space Complexity: O(n * k) – In worst-case each index may store up to k possible modulo values in its DP dictionary.
Solution
We solve the problem using a dynamic programming approach. For each index, we maintain a mapping (dictionary) which stores the length of the longest valid subsequence ending at that index for each possible modulo value r. When processing a pair (i, j) where i < j, calculate r = (nums[i] + nums[j]) % k. Then, if there already exists a chain ending at i with modulo r, extend that chain by including nums[j]. Otherwise, start a new chain from nums[i] and nums[j] with length 2. Finally, the answer is the maximum chain length found over all indices and modulo values, with the fallback that a single element is always valid (length 1) if no chain of length 2 or more exists.