动态规划经典实例---求最大连续子序列的和

本文介绍了一个通过递归方式寻找一维数组中具有最大和的连续子数组的算法实现。该算法首先定义了一个用于计算最大子数组和的函数,并通过分治策略找到左半部分、右半部分的最大子数组和及跨越中间的最大子数组和,最终返回三者中的最大值。
#include <iostream>

using namespace std;

int max(int *x,int low,int high);
int Max3(int x,int y,int z);

int main()
{
    int x[13]={1,2,3,-3,2,-3,4,-2,3,100,2,-101,3};
    cout<<max(x,0,12)<<endl;
    return 0;
}


int max(int *x,int low,int high){

    cout<<low<<" "<<high<<endl;
    if(low>high) return 0;
    if(low==high) return x[low];
    int mid=(low+high)/2;
    int leftmax=max(x,low,mid);
    int rightmax=max(x,mid+1,high);

    int leftbordermax=0;
    int tempsum=0;
    for(int i=mid;i>=low;i--)
    {
        tempsum+=x[i];
        if(tempsum>leftbordermax)
            leftbordermax=tempsum;
    }
    int rightbordermax=0;
    tempsum=0;
    for(int i=mid+1;i<=high;i++)
    {
        tempsum+=x[i];
        if(tempsum>rightbordermax)
            rightbordermax=tempsum;
    }
    return Max3(leftmax,rightmax,leftbordermax+rightbordermax);
}
int Max3(int x,int y,int z){
    return x>y?x>z?x:z:y>z?y:z;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值