3202. Find the Maximum Length of Valid Subsequence II #1938
-
Topics: You are given an integer array A subsequence1
Return the length of the longest valid subsequence of Example 1:
Example 2:
Constraints:
Hint:
Footnotes
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We need to find the maximum length of a valid subsequence in an array where every consecutive pair of elements in the subsequence has the same modulo value when their sum is divided by a given integer k. Approach
Let's implement this solution in PHP: 3202. Find the Maximum Length of Valid Subsequence II <?php
/**
* @param Integer[] $nums
* @param Integer $k
* @return Integer
*/
function maximumLength($nums, $k) {
$n = count($nums);
$ans = 0;
for ($val = 0; $val < $k; $val++) {
$dp = array_fill(0, $k, 0);
for ($i = 0; $i < $n; $i++) {
$r = $nums[$i] % $k;
$s = ($k + $val - $r) % $k;
$candidate = 1;
if ($dp[$s] > 0) {
$candidate = $dp[$s] + 1;
}
if ($candidate > $dp[$r]) {
$dp[$r] = $candidate;
}
if ($dp[$r] > $ans) {
$ans = $dp[$r];
}
}
}
return $ans;
}
// Test cases
// Example 1
$nums1 = [1, 2, 3, 4, 5];
$k1 = 2;
echo "Output: " . maximumLength($nums1, $k1) . "\n"; // Output: 5
// Example 2
$nums2 = [1, 4, 2, 3, 1, 4];
$k2 = 3;
echo "Output: " . maximumLength($nums2, $k2) . "\n"; // Output: 4
?> Explanation:
This approach efficiently checks all possible valid subsequences by leveraging dynamic programming and modular arithmetic, ensuring optimal performance even for the upper constraint limits. |
Beta Was this translation helpful? Give feedback.
We need to find the maximum length of a valid subsequence in an array where every consecutive pair of elements in the subsequence has the same modulo value when their sum is divided by a given integer k.
Approach
Problem Analysis: The key observation is that for any valid subsequence, all consecutive pairs of elements must satisfy (a + b) % k = val for some fixed value val. This condition implies that the residues of the elements in the subsequence must alternate between two residues r0 and r1 such that (r0 + r1) % k = val. Additionally, the subsequence can consist of elements with a single residue r0 where (2 x r0) % k = val.
Dynamic Programming Setup: For each possible value val (fr…