Longest alternating subsequence

A sequence {x1, x2, .. xn} is alternating sequence if its elements satisfy one of the following relations :
x1 < x2 > x3 < x4 > x5..... or x1 >x2 < x3 > x4 < x5.....
Your task is to find the longest such sequence.
算法:二维dp,O(n2)。
代码:

#include
using namespace std;

const int MAXN = 1e5+10;

int T, N;
int a[MAXN];
int ans = 0;
int dp[MAXN][2];
int main() {
    cin >> T;
    while(T--) {
        cin >> N;
        for(int i=1; i<=N; i++) {
            cin >> a[i];
        }
        for(int i=1; i<=N; i++) {
            dp[i][0] = 1;
            dp[i][1] = 1;
        }
        for(int i=1; i<=N; i++) {
            for(int j=i+1; j<=N; j++) {
                if(a[j]a[i])
                    dp[j][1] = max(dp[j][1], dp[i][0]+1);
            }
        }
        ans= 0;
        for(int i=1; i<=N; i++) {
            ans = max({ans, dp[i][0], dp[i][1]});
        }
        cout << ans << endl;
    }
    return 0;
}

参考:
https://www.geeksforgeeks.org/longest-alternating-subsequence/

你可能感兴趣的:(Longest alternating subsequence)