Problem Summary
Given an array of N integers, find the maximal length of its “repeating” subsequence.
“A repeats B” means that subsequence A and B meet the following conditions:
- A and B are not overlapping
- A and B have the same length N, where N>=5
- There is a constant c, s.t. A[i]+c=B[i], 1<=i<=N
Solution
This is a pretty staight forward dynamic programming problem.
Let diff[i]=seq[i]-seq[i-1],2<i<=n. Then the problem is equivalent to finding the maximal length of repeating subsequence of diff.
Let f[i][j] be the maximal length of repeating subsequence ending at i and j in the sequence diff. Apparently, f[i][j] has the same value with f[j][i]. Then the answer to the original problem is max{f[i][j]}+1, 2<=i<n, i+1<j<=n
The dynamic programming equations are:
f[i][j]=f[i-1][j-1]+1, if diff[i]==diff[j] && f[i-1][j-1]<=j-i-2
f[i][j]=f[i-1][j-1], if diff[i]==diff[j] && f[i-1][j-1]==j-i-2
f[i][j]=0, if diff[i]!=diff[j]
Well, for any i, f[i][j] only depends on f[i-1][j], so we can rewrite the eqations:
f[j]=f[j-1]+1, if diff[i]==diff[j] && f[j-1]<=j-i-2
f[j]=f[j-1], if diff[i]==diff[j] && f[j-1]==j-i-2
f[j]=0, if diff[i]!=diff[j]
Using the new equations, we need to do the inner loop backwards. And we can save a lot of space.
Code
|
|