Skip to content

Commit 6bc6e00

Browse files
committed
feat(LeetCode): Solve onlinePlatform/leetcode/leetcoding_challenge/2025/may2025/week3/longest_unequal_adjacent_groups_subsequence_i.cpp
1 parent b75a34f commit 6bc6e00

File tree

1 file changed

+65
-0
lines changed

1 file changed

+65
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
// https://leetcode.com/problems/longest-unequal-adjacent-groups-subsequence-i/description/?envType=daily-question&envId=2025-05-15
2+
3+
#include <algorithm>
4+
#include <vector>
5+
#include <queue>
6+
#include <set>
7+
#include <limits>
8+
#include <map>
9+
#include <unordered_set>
10+
#include <unordered_map>
11+
#include <iterator>
12+
#include <sstream>
13+
#include <iostream> // includes cin to read from stdin and cout to write to stdout
14+
using namespace std; // since cin and cout are both in namespace std, this saves some text
15+
16+
class Solution {
17+
public:
18+
vector<string> getLongestSubsequence(vector<string> &words, vector<int> &groups) {
19+
int NO_PREV = -1;
20+
21+
vector<pair<int, int> > best(words.size());
22+
for (int i = 0; i < words.size(); ++i) {
23+
best[i] = pair{words[i].size(), NO_PREV};
24+
}
25+
26+
int bestIdx = 0;
27+
for (int i = 0; i < words.size(); ++i) {
28+
for (int j = 0; j < i; ++j) {
29+
if (groups[i] == groups[j]) {
30+
continue;
31+
}
32+
int lengthJ = best[j].first + words[i].size();
33+
if (lengthJ > best[i].first) {
34+
best[i] = pair{lengthJ, j};
35+
}
36+
if (best[i].first > best[bestIdx].first) {
37+
bestIdx = i;
38+
}
39+
}
40+
}
41+
42+
deque<string> answer;
43+
while (bestIdx != NO_PREV) {
44+
answer.push_front(words[bestIdx]);
45+
bestIdx = best[bestIdx].second;
46+
}
47+
48+
// return vector(begin(answer), end(answer));
49+
return {begin(answer), end(answer)};
50+
}
51+
};
52+
53+
int main() {
54+
Solution soln;
55+
vector<string> words{"a", "b", "c", "d"};
56+
vector groups{1, 0, 1, 1};
57+
58+
auto result = soln.getLongestSubsequence(words, groups);
59+
for (auto w: result) {
60+
cout << w << " ";
61+
}
62+
cout << endl;
63+
64+
return 0;
65+
}

0 commit comments

Comments
 (0)