給定長度 n 的序列,求最長子序列,滿足:a1 > a2 < a3 > a4 < ...(先降後升交替)。輸出最大長度。
從左向右掃描,只保留「峰」和「谷」。即:
- 找到第一個下降點(a[i] > a[i+1]),將 a[i] 作為第一個峰。
- 之後交替尋找谷(a[j] < a[j+1])和峰(a[j] > a[j+1]),每找到一個長度 +1。
- 等價於:刪除所有單調段中間的元素,只保留局部極值點。
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int T; cin >> T;
while (T--) {
int n; cin >> n;
vector a(n);
for (int& x : a) cin >> x;
if (n <= 1) { cout << n << '\n'; continue; }
int len = 1; // 至少第一個元素
int state = 0; // 0: 找峰(下降), 1: 找谷(上升)
for (int i = 0; i + 1 < n; ++i) {
if (state == 0) {
if (a[i] > a[i+1]) { len++; state = 1; }
} else {
if (a[i] < a[i+1]) { len++; state = 0; }
}
}
cout << len << '\n';
}
return 0;
}
這題是「最長交替子序列」的貪心解法,O(n) 時間,極其高效,是序列極值點提取的典型應用。