Skip to content

Commit 51ac2d3

Browse files
Create Longest Weird Subsequence Explanation.txt
1 parent 91d9b9b commit 51ac2d3

File tree

1 file changed

+70
-0
lines changed

1 file changed

+70
-0
lines changed
Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
We have 3 options for every alphabet - do not include this alphabet,
2+
include it in the increasing sequence
3+
include it in the decreasing sequence
4+
5+
Let f(i, U, D) represent the maximum length of the sequence including the first i characters
6+
where the largest increasing sequence ended with U
7+
and the largest decreasing sequence ended with D
8+
9+
-----
10+
11+
We will choose the maximum of the 3 transitions
12+
13+
1. Case 1, exclude S[i]
14+
15+
This is given by f(i - 1, U, D)
16+
17+
2. Case 2, add it to the increasing sequence
18+
19+
f(i, S[i], D) = max{ 1 + f(i - 1, u, D)}, u <= S[i]
20+
21+
3. Case 3, add it to the decreasing sequence
22+
23+
f(i, U, S[i]) = max{ 1 + f(i - 1, U, d)}, d >= S[i]
24+
25+
-----
26+
27+
void solve()
28+
{
29+
string S;
30+
cin >> S;
31+
32+
int answer = 1;
33+
34+
memset(max_length, 0, sizeof(max_length));
35+
for(int alpha = 0; alpha < NO_OF_ALPHABETS; alpha++)
36+
{
37+
max_length[0][S[0] - 'a'][alpha] = 1;
38+
max_length[0][alpha][S[0] - 'a'] = 1;
39+
}
40+
41+
for(int i = 1; i < S.size(); i++)
42+
{
43+
for(int up_alpha = 0; up_alpha < NO_OF_ALPHABETS; up_alpha++)
44+
{
45+
for(int down_alpha = 0; down_alpha < NO_OF_ALPHABETS; down_alpha++)
46+
{
47+
48+
max_length[i][up_alpha][down_alpha] = max(
49+
max_length[i - 1][up_alpha][down_alpha], max_length[i][up_alpha][down_alpha]);
50+
51+
int current_alpha = S[i] - 'a';
52+
if(up_alpha <= current_alpha)
53+
{
54+
max_length[i][current_alpha][down_alpha] = max(max_length[i][current_alpha][down_alpha],
55+
1 + max_length[i - 1][up_alpha][down_alpha]);
56+
}
57+
58+
if(down_alpha >= current_alpha)
59+
{
60+
max_length[i][up_alpha][current_alpha] = max(max_length[i][up_alpha][current_alpha],
61+
1 + max_length[i - 1][up_alpha][down_alpha]);
62+
}
63+
64+
answer = max(answer, max_length[i][up_alpha][down_alpha]);
65+
}
66+
}
67+
}
68+
69+
cout << answer << "\n";
70+
}

0 commit comments

Comments
 (0)