3201. Find the Maximum Length of Valid Subsequence I #1934
-
Topics: You are given an integer array A subsequence1
Return the length of the longest valid subsequence of A subsequence is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements. Example 1:
Example 2:
Example 3:
Constraints:
Hint:
Footnotes
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We need to find the length of the longest valid subsequence in an array where the sum of every pair of consecutive elements in the subsequence has the same parity (either all even or all odd). The solution involves analyzing the array based on the parity of its elements and leveraging dynamic programming to efficiently compute the result. Approach
Let's implement this solution in PHP: 3201. Find the Maximum Length of Valid Subsequence I <?php
/**
* @param Integer[] $nums
* @return Integer
*/
function maximumLength($nums) {
$count_even = 0;
$count_odd = 0;
$even_len = 0;
$odd_len = 0;
$n = count($nums);
for ($i = 0; $i < $n; $i++) {
if ($nums[$i] % 2 == 0) {
$count_even++;
$even_len = max($even_len, $odd_len + 1);
} else {
$count_odd++;
$odd_len = max($odd_len, $even_len + 1);
}
}
$candidate_same1 = ($count_even >= 2) ? $count_even : 0;
$candidate_same2 = ($count_odd >= 2) ? $count_odd : 0;
$candidate_same = max($candidate_same1, $candidate_same2);
$candidate_alt = max($even_len, $odd_len);
if ($candidate_alt < 2) {
$candidate_alt = 0;
}
return max($candidate_same, $candidate_alt);
}
// Test cases
$nums1 = [1, 2, 3, 4]; // Output: 4
$nums2 = [1, 2, 1, 1, 2, 1, 2]; // Output: 6
$nums3 = [1, 3]; // Output: 2
echo maximumLength($nums1) . "\n";
echo maximumLength($nums2) . "\n";
echo maximumLength($nums3) . "\n";
?> Explanation:
|
Beta Was this translation helpful? Give feedback.
We need to find the length of the longest valid subsequence in an array where the sum of every pair of consecutive elements in the subsequence has the same parity (either all even or all odd). The solution involves analyzing the array based on the parity of its elements and leveraging dynamic programming to efficiently compute the result.
Approach
Problem Analysis: The problem requires finding a subsequence where the sum of every consecutive pair of elements has the same parity. This condition can be satisfied in two scenarios: