分治法求最大连续和的问题

来源:互联网 发布:qq三国辅助软件 编辑:程序博客网 时间:2024/05/22 14:35

分治法求最大连续和

题目

给出一个长为n的序列,求最大连续和

解析

对整个序列进行对半拆分,发现其就只有两种情况,第一种是最大序列完全在左半边或者右半边,第二种情况是左右半边都有,由此我们可以写出代码。

//a stands for the input array,d stands for the lower bound,h snads for the higher boundint 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);}
原创粉丝点击