2900. Longest Unequal Adjacent Groups Subsequence I
You are given a string array
wordsand a binary arraygroupsboth of lengthn.A subsequence of
wordsis alternating if for any two consecutive strings in the sequence, their corresponding elements at the same indices ingroupsare different (that is, there cannot be consecutive 0 or 1).Your task is to select the longest alternating subsequence from
words.Return the selected subsequence. If there are multiple answers, return any of them.
Note: The elements in
wordsare distinct.Example 1:
Input: words = ["e","a","b"], groups = [0,0,1]
Output: ["e","b"]
Explanation: A subsequence that can be selected is
["e","b"]becausegroups[0] != groups[2]. Another subsequence that can be selected is["a","b"]becausegroups[1] != groups[2]. It can be demonstrated that the length of the longest subsequence of indices that satisfies the condition is2.Example 2:
Input: words = ["a","b","c","d"], groups = [1,0,1,1]
Output: ["a","b","c"]
Explanation: A subsequence that can be selected is
["a","b","c"]becausegroups[0] != groups[1]andgroups[1] != groups[2]. Another subsequence that can be selected is["a","b","d"]becausegroups[0] != groups[1]andgroups[1] != groups[3]. It can be shown that the length of the longest subsequence of indices that satisfies the condition is3.
def getLongestSubsequence(self, words: List[str], groups: List[int]) -> List[str]:
res = []
l = len(groups)
res.append(words[0])
for i in range(1,l):
if groups[i] != groups[i-1]:
res.append(words[i])
return res