[LeetCode] Longest Unequal Adjacent Groups Subsequence II

2901. Longest Unequal Adjacent Groups Subsequence II

You are given an integer n, a 0-indexed string array words, and a 0-indexed array groups, both arrays having length n.

The hamming distance between two strings of equal length is the number of positions at which the corresponding characters are different.

You need to select the longest subsequence from an array of indices [0, 1, ..., n - 1], such that for the subsequence denoted as [i0, i1, ..., ik - 1] having length k, the following holds:

  • For adjacent indices in the subsequence, their corresponding groups are unequal, i.e., groups[ij] != groups[ij + 1], for each j where 0 < j + 1 < k.
  • words[ij] and words[ij + 1] are equal in length, and the hamming distance between them is 1, where 0 < j + 1 < k, for all indices in the subsequence.

Return a string array containing the words corresponding to the indices (in order) in the selected subsequence. If there are multiple answers, return any of them.

A subsequence of an array is a new array that is formed from the original array by deleting some (possibly none) of the elements without disturbing the relative positions of the remaining elements.

Note: strings in words may be unequal in length.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
class Solution {
public:
vector<string> getWordsInLongestSubsequence(int n, vector<string>& words, vector<int>& groups) {
unordered_map<string, pair<int,int>> mp;
vector<int> go(n + 100);
int pick = 0, c = 1;
for(int i = 0; i < n; i++) {
int len = words[i].size();
int best = -1, cnt = -1;
for(int j = 0; j < len; j++) {
for(char ch = 'a'; ch <= 'z'; ch++) {
if(ch == words[i][j]) continue;
char ori = words[i][j];
words[i][j] = ch;
if(mp.count(words[i])) {
auto [who, cost] = mp[words[i]];
if(groups[who] != groups[i]) {
if(cnt < cost) {
best = who;
cnt = cost;
}
}
}
words[i][j] = ori;
}
}
cnt = cnt + 1;
cnt = max(cnt, 1);
mp[words[i]] = {i,cnt};
go[i] = best;
if(c < cnt) {
c = cnt, pick = i;
}
}

vector<string> res;
int p = pick;
while(p != -1) {
res.push_back(words[p]);
p = go[p];
}
reverse(begin(res), end(res));
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2023/10/15/PS/LeetCode/longest-unequal-adjacent-groups-subsequence-ii/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.