zoukankan      html  css  js  c++  java
  • 【算法导论C++代码】最大子数组

    #define Inf 65535
    #include <iostream>
    using namespace std;
    void FindMaxCrossingSubarray(int *Array, int low, int mid, int high,
                                 int &maxLeft,int &maxRight, int &sum);
    
    void FindMaxmumSubarry(int *Array,int low,int high,
                           int &relow,int &rehigh,int &resum);
    
    void main()
    {
        int Array[]={13,-3,-25,20,-3,-16,
        -23,18,20,-7,12,-5,-22,15,-4,7};
        cout<<"分治策略,求最大子数组"<<endl;
        int low,high,sum;
        FindMaxmumSubarry(Array,0,15,low,high,sum);
        cout<<"买入天数"<<low<<"卖出天数"<<high<<"总盈利"<<sum<<endl;
        system("pause");
    
    }
    
    void FindMaxCrossingSubarray(int *Array, int low, int mid, int high,
                                 int &maxLeft,int &maxRight, int &sum)
    {
        int leftSum = -Inf;
        sum=0;
        for(int i=mid;i>low;i--)
        {
            sum=sum+Array[i];
            if(sum>leftSum)
            {
                leftSum=sum;
                maxLeft=i;
            }
        }
    
        int rightSum = -Inf;
        sum=0;
        for(int j=mid+1;j<high;j++)
        {
            sum=sum+Array[j];
            if(sum>rightSum)
            {
                rightSum=sum;
                maxRight=j;
            }
        }
    
        sum=leftSum+rightSum;
    }
    void FindMaxmumSubarry(int *Array,int low,int high,
                           int &relow,int &rehigh,int &resum)
    {
        if (high==low)
        {
            relow=low;
            high=rehigh;
            resum=Array[low];
        }
        else
        {
            int mid=(low+high)/2;
            int leftLow,leftHigh,leftSum,
                rightLow,rightHigh,rightSum,
                crossLow,crossHigh,crossSum;
            FindMaxmumSubarry(Array,low,mid,leftLow,leftHigh,leftSum);
            FindMaxmumSubarry(Array,mid+1,high,rightLow,rightHigh,rightSum);
            FindMaxCrossingSubarray(Array,low,mid,high,crossLow,crossHigh,crossSum);
    
            if (leftSum>=rightSum&&leftSum>=crossSum)
            {    
                relow=leftLow;
                rehigh=leftHigh;
                resum=leftSum;
            }
            else if(rightSum>=leftSum&&rightSum>=crossSum)
            {
                relow=rightLow;
                rehigh=rightHigh;
                resum=rightSum;
            }
            else
            {
                relow=crossLow;
                rehigh=crossHigh;
                resum=crossSum;
            }
        }
    }
  • 相关阅读:
    计算GPS WGS_84 两点的距离
    极路由4_开ssh_刷breed
    aes-256-gcm_python3_php7_golang
    nginx_非标准端口_同端口_http_自动跳转_https
    配置sshd_除了特定ip外_仅密钥登录
    使用scp命令实现服务器之间文件传输
    Java防止重复提
    mysql使用SUBSTRING_INDEX截取部分字符串
    SEO大杀器rendertron安装
    PIC16 bootloader之I2C bootloader
  • 原文地址:https://www.cnblogs.com/fastcam/p/4778367.html
Copyright © 2011-2022 走看看