• 数组中最大子数组之和


    题目

    [1, -2, 3, 5, -3, 2] 返回:8
    [0, -2, 3, 5, -1, 2] 返回:9
    [-9, -2, -3, -5, -3] 返回:-2

    主要程序

    int MaxSum4(int *A, int n,int &beg,int &end)
    {
        if(A==NULL||n<=1)
        {
            cout<<"error input"<<' ';
            exit(0);
        }
        if(n==1)
            return A[0];
        int pos = 0;
        int CurSum = A[0];
        int MaxSum = A[0];
        for(int i = 1; i<n;++i)
        {
            if(CurSum<=0)
                CurSum = 0;
            CurSum += A[i];
            if(CurSum>=MaxSum)
            {
                MaxSum = CurSum;
                pos = i;
            }
        }
        int pos1 = 0,max1 = A[0];
        CurSum = A[0]; 
        for(int i = 1;i<=n-1;++i)
        {
            CurSum += A[i];
            if(CurSum>=max1)
            {
                max1 = CurSum;
                pos1 = i;
            }
        }
        CurSum = A[n-1];
        int pos2 = n-1, max2 = A[n-1];
        for(int j = n-2; j>=0; --j)
        {
            CurSum += A[j];
            if(CurSum>=max2)
            {
                max2 = CurSum;
                pos2 = j;
            }
        }
        int sum = 0;
        if(pos1>=pos2)
        {
            for(int i = 0; i<n; ++i)
                sum+=A[i];
        }
        else
        {
            for(int i = 0; i<=pos1; ++i)
            {
                sum+=A[i];
            }
            for(int j = n-1; j>=pos2; --j)
            {
                sum+=A[j];
            }
        }
        int temp = MaxSum>sum?MaxSum:sum;
        if(MaxSum==temp)
        {
            end = pos;
            while(temp!=0)
            {
                temp-=A[pos--];
            }
            beg = ++pos;
            return MaxSum;
        }
        else
        {
            if(pos1>=pos2)
            {
                beg = 0;
                end = n-1;
            }
            else
            {
                end = pos2;
                beg = pos1;
            }
            return sum;
        }
        return MaxSum>sum?MaxSum:sum;
    }
  • 相关阅读:
    linux系统swap分区容量扩展
    linux系统lv_root分区容量扩展
    linux系统创建新LV,挂载新分区。
    linux 服务器重启后lvm 变成inactive状态解决
    Linux下使用fdisk扩大分区容量
    go语言 调用飞书群消息机器人接口
    SpringCloud Sentinel 学习笔记
    Git 笔记整理
    SpringBoot 整合 RabbitMQ 学习笔记
    js递归生成树形结构-vue
  • 原文地址:https://www.cnblogs.com/zhaocen/p/6644447.html
Copyright © 2020-2023  润新知