题解 | #最大连续子序列#
最大连续子序列
https://www.nowcoder.com/practice/afe7c043f0644f60af98a0fba61af8e7
//https://www.nowcoder.com/practice/afe7c043f0644f60af98a0fba61af8e7?tab=answerKey #include <iostream> #include <algorithm> #include <vector> using namespace std; int main() { int n; while (cin >> n) { if(n==0) continue; vector<int> num(n); //? n为0时会怎么处理 int dp[n]; int flag = 0; int maxn = 0; int left = 0; int right = 0; int tem = 0; for(auto &c:num){ cin >> c; if(c>=0) flag = 1; } if(!flag){ cout << 0 << ' ' << num.front() << ' ' << num.back() << endl; continue; } for(int i = 0;i<n;i++){ if(i==0){ dp[i] = num[i]; maxn = dp[i]; left = i; right = i; } else{ dp[i] = max(num[i], dp[i-1]+num[i]); if(dp[i]==num[i]) tem = i; if(maxn<dp[i]){ maxn = dp[i]; left = tem; right = i; } } } cout << maxn << ' ' << num[left] << ' ' << num[right] << endl; } }