Find the Maximum Length of Valid Subsequence II Problem
Description
LeetCode Problem 3202.
You are given an integer array nums and a positive integer k.
A subsequence sub of nums with length x is called valid if it satisfies:
(sub[0] + sub[1]) % k == (sub[1] + sub[2]) % k == ... == (sub[x - 2] + sub[x - 1]) % k.
Return the length of the longest valid subsequence of nums.
Example 1:
Input: nums = [1,2,3,4,5], k = 2
Output: 5
Explanation:
The longest valid subsequence is [1, 2, 3, 4, 5].
Example 2:
Input: nums = [1,4,2,3,1,4], k = 3
Output: 4
Explanation:
The longest valid subsequence is [1, 4, 1, 4].
Constraints:
2 <= nums.length <= 10^31 <= nums[i] <= 10^71 <= k <= 10^3
Solution
Approach: Dynamic Programming on Remainders
If a subsequence a1, a2, a3, ... has all pair sums with the same remainder mod k, then (a1 + a2) % k == (a2 + a3) % k, so a1 % k == a3 % k. Hence all elements at odd positions share one remainder and all elements at even positions share another.
Let f[x][y] be the longest valid subsequence seen so far whose last element has remainder x and the one before it has remainder y. For each number, reduce it to x = num % k. For every possible common pair-sum remainder j, the previous element must have remainder y = (j - x + k) % k, so f[x][y] = f[y][x] + 1. The answer is the largest f value.
Complexity: O(nk) time and O(k2) space.
class Solution:
def maximumLength(self, nums: List[int], k: int) -> int:
f = [[0] * k for _ in range(k)]
ans = 0
for x in nums:
x %= k
for j in range(k):
y = (j - x + k) % k
f[x][y] = f[y][x] + 1
ans = max(ans, f[x][y])
return ans