编程珠玑 第 8 章
求一个整型数组中相邻子向量的最大和
31 | -41 | 59 | 26 | -53 | 58 | 97 | 93 | -23 | 84 |
O(n3)
int maxsofar = 0; for (int i = 0; i < n; i++) { for (int j = i; j < n; j++) { sum = 0; for (int k = i; k <= j; k++) { sum += a[k]; } maxsofar = max(maxsofar, sum); } }
O(n2)
int maxsofar = 0; for (int i = 0; i < n; i++) { int sum = 0; for (int j = i; j < n; j++) { sum += a[j]; maxsofar = max(maxsofar, sum); } }
O(n2) 记忆
int maxsofar = 0; cumarr[-1] = 0; // cumarr 计算从 a[0] 到 a[i] 的和 for (int i = 0; i < n; i++) { cumarr[i] = a[i] + cumarr[i-1]; } int sum; for (int i = 0; i < n; i++) { for (int j = i; j < n; j++) { sum = cumarr[j] - cumarr[i-1]; maxsofar = max(maxsofar, sum); } }
O(nlogn)
利用归并实现的,注意在求左边部分的时候要从中间往 l 那边靠.. 这样才能保证和右边相连,表示好难写….
void max_sum(int l, int r) { if (l > r) { return 0; } if (l == r) { return a[l]; } int mid = (l+r) / 2; int lmax = 0; int lsum = 0; for (int i = mid; i >= l; i--) { lsum += a[i]; lmax = max(lsum, lmax); } int rmax = 0; int rsum = 0; for (int i = mid+1; i <= r; i++) { rsum += a[i]; rmax = max(rsum, rmax); } return max(lmax+rmax, max(maxsum(l, mid), maxsum(mid+1, r))); }
O(n)
膜拜…
int maxsofar = 0; int maxendinghere = 0; for (int i = 0; i < n; i++) { maxendinghere = max(maxendinghere, 0); maxsofar = max(maxsofar, maxendinghere); }
到此结束了…..88