升级版的最大子列和问题
没什么好说的
#include <iostream> using namespace std; int main() { int n; cin >> n; int *a = (int*)malloc(n*sizeof(int)); for (int i = 0; i < n; i++){ cin >> a[i]; } int max = -1,sum=0; int maxl = a[0], maxr = a[0]; int l = a[0],r=a[0]; bool negative = true; for (int i = 0; i < n; i++){ sum += a[i]; if (sum>max){ max = sum; maxl = l; maxr = a[i]; negative = false; } else if (sum < 0){ sum = 0; l = a[i + 1]; } } if (negative == true){ max = 0; maxl = a[0]; maxr = a[n - 1]; } cout << max << " " << maxl << " " << maxr; }
时间: 2024-10-19 10:17:41