Files
python/C++专题课程/NOIP算法总结/最大连续子序列和/最大连续子序列和.cpp
HuangHai 1f397eca87 'commit'
2025-08-30 18:35:01 +08:00

28 lines
685 B
C++
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#include<bits/stdc++.h>
#define maxn 1000
using namespace std;
int dp[maxn];
int main() {
int n;
scanf("%d", &n);
int a[maxn];
for (int i = 0; i < n; i++) {
scanf("%d", &a[i]);
}
dp[0] = a[0];//边界 (结果总是确定的,动态规划总是从这些边界出发)
for (int i = 0; i < n; i++) {
dp[i] = max(a[i], dp[i - 1] + a[i]);//递推式
}
//dp[i]存放以a[i]结尾的连续序列的最大和,需要遍历i得到最大的才是结果
int k = 0;
for (int i = 0; i < n; i++) {
if (dp[i] > dp[k]) {
k = i;
}
}
printf("%d\n", dp[k]);
return 0;
}