- 容易发现,直接用普通dp的话每一个下标后面都有 个备选,时间复杂度就是 了,会超时,所以我们要找一个备选只有 个的方法。
- 所以可以用值来做dp。
#include <bits/stdc++.h>
using namespace std ;
int n , a[100005] , ans ;
map <int , int> mp ;
int main() {
cin >> n ;
for(int i = 1 ; i <= n ; i ++) {
cin >> a[i] ;
}
for(int i = 1 ; i <= n ; i ++) {
int cur = 1 ;
if(mp.count(a[i] - 1)) {
cur = max(cur , mp[a[i] - 1] + 1) ;
}
if(mp.count(a[i] + 1)) {
cur = max(cur , mp[a[i] + 1] + 1) ;
}
ans = max(ans , (mp[a[i]] = max(mp[a[i]] , cur))) ;
}
cout << ans ;
return 0 ;
}
- 时间复杂度: 。
- 空间复杂度: 。
暂无评论