I am trying to solve a variant of a problem I asked earlier:
Given a string of parentheses (length <= 1,000,000) and a list of range queries, find the longest subsequence of balanced parentheses within each of the ranges for each of the <= 100,000 queries
I found this other SO question that is similar but only has an O(N^3) algorithm.
I believe that a DP solution of the form dp[i, j] = longest balanced subsequence in [i .. j]
should work because once computed, this would enable to to answer all of the range queries just by querying the DP table. However, even an O(N^2) solution to this problem would exceed the time limits due to the large possible input string length.
Further, the trick of using a stack to keep track of matching parentheses no longer directly works because you are looking for subsequences, not substrings.
I have a method which I think might work but am not sure of:
The length of the longest subsequence of balanced parentheses within an interval is the sum of the lengths of the longest non-overlapping substrings of balanced parentheses within that interval.
For example, if you have the string
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
) ) ( ( ) ( ( ) ) ) ) ( ( ) )
The length of the longest subsequence of balanced parentheses in the interval [0, 8] (inclusive) is 5. This length is equal to that of the sum of the lengths of the longest non-overlapping substrings within the interval: "( )" + "( ( ) )".
Will this method always hold, or is there a better way?