Find the Maximum Length of Valid Subsequence III Problem
Description
LeetCode Problem 4110.
You are given an integer array nums and a positive integer k.
A subsequence of nums is valid if the sum of every pair of adjacent elements in the subsequence is divisible by k.
A subsequence of length 1 is always valid.
Return the length of the longest valid subsequence of nums.
Example 1:
Input: nums = [1,2,3,4,5], k = 3
Output: 4
Explanation:
- Pick the subsequence [1, 2, 4, 5].
- The adjacent sums are 1 + 2 = 3, 2 + 4 = 6, and 4 + 5 = 9, all divisible by 3.
- No valid subsequence longer than 4 exists.
Example 2:
Input: nums = [5,10,15], k = 5
Output: 3
Explanation:
- Pick the whole array [5, 10, 15].
- The adjacent sums are 5 + 10 = 15 and 10 + 15 = 25, both divisible by 5.
- Every element is a multiple of 5, so any two elements can be adjacent in a valid subsequence, and the answer is 3.
Example 3:
Input: nums = [1,3,5,7,9], k = 4
Output: 5
Explanation:
- Pick the whole array [1, 3, 5, 7, 9].
- The adjacent sums are 1 + 3 = 4, 3 + 5 = 8, 5 + 7 = 12, and 7 + 9 = 16, all divisible by 4.
- The remainders alternate between 1 and 3, which add to 4, so the answer is 5.
Constraints:
2 <= nums.length <= 10^51 <= nums[i] <= 10^91 <= k <= 10^5
Solution
Approach: Dynamic Programming by Remainder
Two neighbors u and v in a valid subsequence satisfy (u + v) % k == 0, so their remainders r and (k - r) % k are complementary. A valid subsequence therefore alternates between at most two remainders, and we only need to remember the best length by the remainder of the last element.
Let best[r] be the longest valid subsequence seen so far that ends with remainder r. For each number v with x = v % k and y = (k - x) % k, we can append v to a subsequence ending in remainder y, or start a new one, so best[x] = max(best[x], best[y] + 1). The answer is the largest best value (at least 1).
Complexity: O(n + k) time and O(k) space.
class Solution:
def maximumLength(self, nums: List[int], k: int) -> int:
# Neighbours must have remainders r and (k - r) % k, so a valid subsequence alternates between two remainders.
# best[r]: the longest valid subsequence so far that ends with remainder r
best = [0] * k
ans = 1
for v in nums:
x = v % k
y = (k - x) % k
best[x] = max(best[x], best[y] + 1)
ans = max(ans, best[x])
return ans