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

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

要求:

 1、 要求程序必须能处理1000 个元素;

2、 每个元素是int32 类型的,出现子数组之和大于整型表示的最大范围会出现什么情况;

3、 输入一个整形数组,数组里有正数也有负数。 数组中连续的一个或多个整数组成一个子数组,每个子数组都有一个和。 求所有子数组的和的最大值。

4、要求时间复杂度为O(n)。

思路:

  利用random函数产生随机数;

  利用for语句实现最大子数组的求和

代码:

#include<iostream>

#include<stdlib.h>

#include<iomanip>

#include<time.h>

using namespace std;

#define Max  100000

void main ()

{   

    int n,array[Max];   

    cout<<"请输入数组的长度:";   

    cin>>n;   

    cout<<"产生的n个数为"<<endl;   

    for(int i=0;i<n;)   

        {               array[i]=-Max/10+rand()%(Max*2+1);   

                         cout<<setw(5)<<array[i]<<" ";   

                         i++;    if(i%5==0)     cout<<endl;   

       }   

       cout<<endl;   

       int sum=array[0],max=array[0];   

       for(int i=0;i<n;i++)   

       {       

            sum=sum+array[i];    

            if(sum<array[i])     

                   sum=array[i];    

           if (max<sum)     

                     max=sum;       

       }   

     cout<<"最大的子数组和是:"<<max<<endl;

}

截图:

总结:

random函数用法:

random所在的头文件  stdlib.h
int random(int num);
random函数返回一个0~num-1之间的随机数. random(num)是在stdlib.h中的一个宏定义. num和函数返回值都是整型数.
在c++中 可以用
a+rand()%n产生由a~n的随机数
原文地址:https://www.cnblogs.com/mingning/p/4537638.html