int maxn = 0, s = 0, t = 0; int sum = 0, pos = 1; for (int i = 1; i <= k; i++) { sum += a[i]; if (sum < 0) { pos = i + 1; sum = 0; } elseif (sum > maxn) { s = pos; t = i; maxn = sum; } }
intmaxsum(int *A, int x, int y)// 返回数组在左闭右开区间[x,y)中的最大连续和 { if (y - x == 1) return A[x]; // 只有一个元素,直接返回 int m = x + (y - x) / 2; // 划分成[x,m)和[m,y) int maxn = max(maxsum(A, x, m), maxsum(A, m, y)); // 递归求解 int v = 0, L = A[m - 1], R = A[m]; for (int i = m - 1; i >= x; i--) L = max(L, v += A[i]); // 找从分界点开始往左的最大连续和L v = 0; for (int i = m; i < y; i++) R = max(R, v += A[i]); // 找从分界点开始往右的最大连续和R returnmax(maxn, L + R); // max(左区间,右区间,横跨区间) }