返回一个整数数组中最大子数组的和

输入一个整形数组,数组里有正数也有负数。

数组中连续的一个或多个整数组成一个子数组,每个子数组都有一个和。

如果数组A[0]……A[j-1]首尾相邻,允许A[i-1], …… A[n-1], A[0]……A[j-1]之和最大。

同时返回最大子数组的位置。

求所有子数组的和的最大值。——摘要

编程代码

#include <iostream>  
#include<ctime>
#define Num 10000
using namespace std;   
int DTGH_Sum(int a[],int n) 
{
    int sum = 0;
    int *b = (int *) malloc(n * sizeof(int));    
    b[0] = a[0];
    for(int i = 1; i < n; i++)
    {
        if(b[i-1] > 0)
            b[i] = b[i - 1] + a[i];
        else
            b[i] = a[i];
    }
    for(int j = 0; j < n; j++)
    {
        if(b[j] > sum)
            sum = b[j];
    }
    delete []b;       
    return sum;
}
int main()   
{   int temp,b; 
    int sum=0; 
    int i; 
    int a1,a2; 
    int a[Num];
    int length=0;
    while (length==NULL||length == 0)
     {
      cout<<"请输入数组长度:";
      cin>>length;
     }
    cout<<"生成随机数组: "<<endl; 
    srand((unsigned)time(NULL)); 
    for(i=0;i<length;i++)
    {
        if(rand()%2==0)
        {
            a[i]=rand()%50;
        }
        else
        {
            a[i]=(-1)*rand()%50;
        }    
            cout<<a[i]<<" ";    
    }
    cout<<endl;    
    cout<<"此首尾相连的数组中最大子数组的和有以下几种可能:"<<endl; 
    cout<<"第1种排列方式:"<<endl; 
    for( i=0;i<length;i++) 
    {
        cout<<a[i]<<"  ";
    } 
    cout<<"最大子数组和为:"<<DTGH_Sum(a,length)<<endl; 
    a1=DTGH_Sum(a,length); 
    for(b=1;b<length;b++) 
    { 
        temp=a[0]; 
    for(i=1;i<=length;i++) 
     {   
        a[i-1]=a[i]; 
              
     } 
       a[length-1]=temp; 
       cout<<"第"<<b+1<<"种排列方式:"<<endl; 
       for( i=0;i<length;i++) 
       {
           cout<<a[i]<<"  ";
       } 
       cout<<"最大子数组和为:"<<DTGH_Sum(a,length)<<endl; 
       if(DTGH_Sum(a,length)>=sum) 
       {
           sum=DTGH_Sum(a,length);
       } 
    }  
      a2=sum; 
      cout<<endl; 
      if(a1>=a2) 
      {
          cout<<"综上,最大的子数组和为:"<<a1<<endl;
      } 
      else
      {
          cout<<"综上,最大的子数组和为:"<<a2<<endl;
      }   
    return 0;   
}

转载于:https://www.cnblogs.com/yang97/p/10247819.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值