2900. Longest Unequal Adjacent Groups Subsequence I #1687
-
Topics: You are given a string array Your task is to select the longest alternating subsequence1 from Formally, you need to find the longest subsequence of an array of indices Return the selected subsequence. If there are multiple answers, return any of them. Note: The elements in Example 1:
Example 2:
Constraints:
Hint:
Footnotes
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We need to find the longest subsequence of words such that adjacent elements in the subsequence have different corresponding values in the binary array ApproachThe greedy approach works by iterating through the
This approach ensures that we build the longest possible alternating subsequence by making locally optimal choices at each step. Let's implement this solution in PHP: 2900. Longest Unequal Adjacent Groups Subsequence I <?php
/**
* @param String[] $words
* @param Integer[] $groups
* @return String[]
*/
function getLongestSubsequence($words, $groups) {
$n = count($words);
if ($n == 0) {
return [];
}
$result = array($words[0]);
$lastGroup = $groups[0];
for ($i = 1; $i < $n; $i++) {
if ($groups[$i] != $lastGroup) {
$result[] = $words[$i];
$lastGroup = $groups[$i];
}
}
return $result;
}
// Example 1:
$words1 = ["e","a","b"];
$groups1 = [0,0,1];
print_r(getLongestSubsequence($words1, $groups1));
// Example 2:
$words2 = ["a","b","c","d"];
$groups2 = [1,0,1,1];
print_r(getLongestSubsequence($words2, $groups2));
?> Explanation:
This method efficiently constructs the required subsequence in linear time, making it optimal for the given problem constraints. |
Beta Was this translation helpful? Give feedback.
We need to find the longest subsequence of words such that adjacent elements in the subsequence have different corresponding values in the binary array
groups
. This can be efficiently achieved using a greedy approach.Approach
The greedy approach works by iterating through the
groups
array and constructing the subsequence by selecting each element whose group value differs from the previous element in the subsequence. This ensures that we always take the earliest possible elements that allow for the maximum length of alternating groups. Here are the steps:words
array since it will always be part of the subsequence.