算法最大字段和

实现最大字段和算法,分治法 C++实现.。

#include <iostream>
using namespace std;

int Max(int array[], int left, int right);

int main(int argc, const char * argv[]) {
    int array[] = {-20, 11, -4, 13, -5, -2}; // 最大子段和为20
    int sum = Max(array, 0, 5);
    cout<<sum<<endl;
    return 0;
}


int Max(int array[], int left, int right) {
    int sum;
    int center;
    int leftSum; // 分治的左边值的和
    int rightSum; // 分治的右边边值的和
    int middeLeftSum = 0; // 中点左边和
    int middeRightSum = 0; // 中点右边和
    int tempmiddeLeftSum = 0; // 辅助求中点左边最大值,下同。
    int tempmiddeRightSum = 0; 
    // 求出中点索引
    center = (left + right) / 2;
    
    if (left == right) {
        return array[left];
    }
    
    leftSum = Max(array, left, center);
    rightSum = Max(array, center + 1, right);
    
    for (int i = center; i >= left; i--) {
        tempmiddeLeftSum += array[i];
        if (middeLeftSum <= tempmiddeLeftSum) {
            middeLeftSum = tempmiddeLeftSum;
        }
        
    }
    
    for (int i = center + 1; i <= right; i++) {
        tempmiddeRightSum += array[i];
        if (middeRightSum <= tempmiddeRightSum) {
            middeRightSum = tempmiddeRightSum;
        }
        
    }
    
    int middleSum = middeLeftSum + middeRightSum;
    
    sum = leftSum >= rightSum? leftSum : rightSum;
    
    sum = middleSum > sum? middleSum : sum;
    
    return sum;
}

点赞