分治法求最大連續和
題目
給出一個長爲n的序列,求最大連續和解析
對整個序列進行對半拆分,發現其就只有兩種情況,第一種是最大序列完全在左半邊或者右半邊,第二種情況是左右半邊都有,由此我們可以寫出代碼。
//a stands for the input array,d stands for the lower bound,h snads for the higher bound
int maxsum(int *a,int d,int h)
{
int temp, l, r, tmax;
if (h - d == 1)
return a[d];
int m = (d + h) / 2;//confirm m is not greater than the real middle number
tmax = max(maxsum(a, d, m), maxsum(a, m, h));
temp = 0;
l = a[m - 1];
for (int i = m - 1; i >= d; i++)
l = max(l, temp += a[i]);
temp = 0;
r = a[m];
for (int i = m; i < h; i++)
r = max(temp += a[i], l);
return max(tmax, l + r);
}