题解 | #游游的最长稳定子数组#
游游的最长稳定子数组
https://www.nowcoder.com/practice/ea7098b7960348f6915e252f0c4debcc
从第二个元素开始遍历数组,如果当前元素和前一个元素之差的绝对值不超过1,则当前稳定子数组的长度加1,否则,重置当前稳定子数组的长度为1,然后维护一个最大的答案即可
#include <bits/stdc++.h> using namespace std; #define int long long const int N = 2e5 + 5; int __t = 1, n, a[N]; void solve() { cin >> n; int sum = 1, ans = 1; for (int i = 1; i <= n; i++) cin >> a[i]; for (int i = 2; i <= n; i++) { if (abs(a[i] - a[i - 1]) <= 1) sum++; else sum = 1; ans = max(ans, sum); } cout << ans << '\n'; return; } int32_t main() { #ifdef ONLINE_JUDGE ios::sync_with_stdio(false); cin.tie(0); #endif // cin >> __t; while (__t--) solve(); return 0; }