b_pat_最大子序列和起始端点(讨论左、右端点更新时机)
you are supposed to find the largest continue sum, together with the first and the last numbers of the maximum subsequence.
方程:f[i]=max(f[i-1]+A[i], A[i])
新颖的地方在与求LIS的端点元素:
- 左端点更新时机:当 f[i-1]+A[i]<A[i] 时,我们认为[1,i)这一段的LIS比A[i]还要差,那我们不可能取到 [1,i) 这些元素作为左端点,但i还是偶可能的,所以我需要保存i
- 右端点更新时机:当 f[i]>ans 时,我们认为找到了一段新的LIS,此时更新右端点即可
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int inf=0x3f3f3f3f;
int main() {
std::ios::sync_with_stdio(false); cin.tie(0); cout.tie(0);
int n, allneg=1; cin>>n;
ll A[n+1], f[n+5];
for (int i=1; i<=n; i++) {
cin>>A[i];
if (A[i]>=0) allneg=false;
}
if (allneg) {
cout << 0 << ' ' << A[1] << ' ' << A[n];
} else {
memset(f, -inf, sizeof f);
int lastl=0, l=0, r=0, ans=-inf;
for (int i=1; i<=n; i++) {
f[i]=max(A[i], f[i-1]+A[i]);
if (f[i-1]+A[i]<A[i]) {
lastl=A[i];
}if (f[i]>ans) {
ans=f[i], l=lastl, r=A[i];
}
}
cout << ans << ' ' << l << ' ' << r;
}
cout << '\n';
return 0;
}
复杂度分析
- Time:\(O(n)\),
- Space:\(O(n)\),