最大子段和 对应洛谷P1115 代码见下
cpp
#include<iostream>
using namespace std;
#define maxn 200010
#define type int
#define inf -1000000000
type getMSS(int n, type a[], type dp[]){
//dp[i]代表以第i个数结尾的最大子段和
type ans = inf;
dp[0] = 0;
for(int i=1; i<=n; ++i){
dp[i] = a[i] + max(dp[i-1], 0);
ans = max(dp[i], ans);
}
return ans;
}
type dp[maxn];
type a[maxn];
int main(){
int n;
cin >> n;
for(int i=1; i<=n; ++i){
cin >> a[i];
}
cout << getMSS(n, a, dp) << endl;
return 0;
}
代码练习1 对应蓝桥云课 区间最大子序列和 代码见下
cpp
#include<iostream>
using namespace std;
#define maxn 2010
#define type int
#define inf -1000000000
type getMSS(int n, type a[], type dp[]){
//dp[i]代表以第i个数结尾的最大子段和
type ans = inf;
dp[0] = 0;
for(int i=1; i<=n; ++i){
dp[i] = a[i] + max(dp[i-1], 0);
ans = max(dp[i], ans);
}
// 转换成前i个元素的最大子段和
dp[0] = inf;
for(int i=1; i<=n; ++i){
dp[i] = max(dp[i], dp[i-1]);
}
return ans;
}
type dp[maxn][maxn];
type a[maxn];
int main(){
int n;
cin >> n;
for(int i=1; i<=n; ++i){
cin >> a[i];
}
for(int i=1; i<=n; ++i){
getMSS(n-i+1, &a[i-1], dp[i]);
}
int t;
cin >> t;
while(t--){
int l, r;
cin >> l >> r;
cout << dp[l][r-l+1] << endl;
}
}
代码练习 3 基德的冒险之旅 蓝桥云课 代码见下
cpp
#include<iostream>
using namespace std;
#define maxn 100010
#define type long long
#define inf -10000000000011
type getMSS(int n, type a[], type dp[]){
//dp[i]代表以第i个数结尾的最大子段和
type ans = inf;
dp[0] = 0;
for(int i=1; i<=n; ++i){
dp[i] = a[i] + max(dp[i-1], (type)0);
ans = max(dp[i], ans);
}
// 转换成前i个元素的最大子段和
dp[0] = inf;
for(int i=1; i<=n; ++i){
dp[i] = max(dp[i], dp[i-1]);
}
return ans;
}
void swap(int n, type a[]){
for(int i=1; i<=n/2; ++i){
swap(a[i], a[n+1-i]);
}
}
type dppre[maxn], dppost[maxn];
type a[maxn];
int main(){
int n, k;
cin >> n >> k;
for(int i=1; i<=n; ++i){
cin >> a[i];
}
getMSS(n, a, dppre);
swap(n, a);
getMSS(n, a, dppost);
swap(n, dppost);
type ans = inf;
for(int i=1; i+k+1 <=n; ++i){
ans = max(ans, dppre[i]+dppost[i+k+1]);
}
cout << ans << endl;
return 0;
}
代码练习 4 对应蓝桥云课 可删除数组的最大子数组和 代码见下
cpp
#include <iostream>
using namespace std;
#define maxn 100010
#define maxk 101
#define inf -1000000000
int a[maxn];
int dp[maxn][maxk];
int main()
{
int n, k;
cin >> n >> k;
for(int i=1; i<=n; ++i){
cin >> a[i];
}
dp[0][0] = 0;
for(int j=1; j<=k; ++j){
dp[0][j] = inf;
}
for(int i=1; i<=n; ++i){
dp[i][0] = a[i] + max(dp[i-1][0], 0);
for(int j=1; j<=k; ++j){
dp[i][j] = max(dp[i-1][j] + a[i], dp[i-1][j-1]);
}
}
int ans = inf;
for(int i=1; i<=n; ++i){
for(int j=0; j<=k; ++j){
ans = max(ans, dp[i][j]);
}
}
cout << ans << endl;
// 请在此输入您的代码
return 0;
}