Social feed~25 min2s · 256 MBtarget O(n²) time, O(n) spaceclassic twin: lc-516dp
A social app lets people edit the caption of a post. A new feature offers a symmetrical version of the caption: it deletes some letters so that what is left reads the same forwards and backwards.
The remaining letters must stay in their original order, and the app wants to keep as many letters as possible.
Write longest_palindromic_subsequence(text).
text is the caption, lowercase letters.text in their original order, and may drop any letters between them.Input: text = "abdbca"
Output: 5Let best[i][j] be the length of the longest palindromic subsequence of the piece of text from i to j. A piece of one letter has the answer 1. When the end letters match, they wrap the best answer for the piece inside, which gives best[i + 1][j - 1] + 2. When they differ, one end is dropped: the answer is the larger of best[i + 1][j] and best[i][j - 1].
| start \ end | 0 (a) | 1 (b) | 2 (d) | 3 (b) | 4 (c) | 5 (a) |
|---|---|---|---|---|---|---|
| 5 (a) | 1 | |||||
| 4 (c) | 1 | 1 | ||||
| 3 (b) | 1 | 1 | 1 | |||
| 2 (d) | 1 | 1 | 1 | 1 | ||
| 1 (b) | 1 | 1 | 3 | 3 | 3 | |
| 0 (a) | 1 | 1 | 1 | 3 | 3 | 5 |
The cell for the whole text holds 5. The kept letters are a, b, d, b, a.
Input: text = "abc"
Output: 1No letter appears twice, so only one letter can be kept.
Input: text = "aaaa"
Output: 4The whole caption reads the same backwards.
1 ≤ len(text) ≤ 1000text contains lowercase letters onlyA caption of 1,000 letters has 1,000 × 1,001 / 2 = 500,500 pieces, so a table with one entry for each piece is about half a million small steps. The number of ways to keep letters is 2^1000, a number of 302 digits, so trying them all is impossible.