一、題目:返回一個整數數組中最大子數組的和。
二、要求:
要求程序必須能處理1000 個元素;
每一個元素是int32 類型的;
輸入一個整形數組,數組裏有正數也有負數。
數組中連續的一個或多個整數組成一個子數組,每一個子數組都有一個和。
求全部子數組的和的最大值。要求時間複雜度爲O(n)。
三、設計思路:
將數組大小定義爲1000,對於每一個元素定義爲int32類型,將求和函數設置爲int 類型,這樣能夠方便觀測數據的溢出,讓數組元素能夠超出範圍。
要求程序必須能處理1000 個元素;
每一個元素是int32 類型的;
輸入一個整形數組,數組裏有正數也有負數。
數組中連續的一個或多個整數組成一個子數組,每一個子數組都有一個和。
求全部子數組的和的最大值。要求時間複雜度爲O(n)。
三、設計思路:
將數組大小定義爲1000,對於每一個元素定義爲int32類型,將求和函數設置爲int 類型,這樣能夠方便觀測數據的溢出,讓數組元素能夠超出範圍。
4.程序代碼:
#include<iostream>
#include<time.h>
#include<conio.h>
#define N 1000
using namespace std;
void RandIn(int IntNum,int A[]) //隨機生成數組
{
cout<<"整數內容"<<endl;
for(int i=0;i<IntNum;i++)
{
A[i]=rand()-rand();
cout<<A[i];
if(i%15==4)
cout<<endl;
else
cout<<'\t';
}
}
void SelMax(int IntNum,int A[],auto &sum)
{
int buffer=0;
int count1=0; //求和的數值個數
int count2=0; //進行的運算次數
for(int j=0;j<=IntNum;j++)
{
if(j==IntNum)
{
j=0;
}
buffer+=A[j];
count1++;
count2++;
if(buffer<0)
{
buffer=0;
count1=0;
}
if(sum<buffer)//sum始終記錄下存在的最大和
{
sum=buffer;
}
{
break;
}
}
}
void main()
{
int IntNum;
int A[N];
int q=0;
while(q==0)
{
auto sum=0;
srand((unsigned)time(NULL));
cout<<"請輸入數組元素的個數:";
cin>>IntNum;
RandIn(IntNum,A);
SelMax(IntNum,A,sum);
cout<<endl;
cout<<sum<<endl;
cout<<"是否繼續測試(輸入0則繼續不然中止)";
cin>>q;
system("cls");
}
}
#include<time.h>
#include<conio.h>
#define N 1000
using namespace std;
void RandIn(int IntNum,int A[]) //隨機生成數組
{
cout<<"整數內容"<<endl;
for(int i=0;i<IntNum;i++)
{
A[i]=rand()-rand();
cout<<A[i];
if(i%15==4)
cout<<endl;
else
cout<<'\t';
}
}
void SelMax(int IntNum,int A[],auto &sum)
{
int buffer=0;
int count1=0; //求和的數值個數
int count2=0; //進行的運算次數
for(int j=0;j<=IntNum;j++)
{
if(j==IntNum)
{
j=0;
}
buffer+=A[j];
count1++;
count2++;
if(buffer<0)
{
buffer=0;
count1=0;
}
if(sum<buffer)//sum始終記錄下存在的最大和
{
sum=buffer;
}
{
break;
}
}
}
void main()
{
int IntNum;
int A[N];
int q=0;
while(q==0)
{
auto sum=0;
srand((unsigned)time(NULL));
cout<<"請輸入數組元素的個數:";
cin>>IntNum;
RandIn(IntNum,A);
SelMax(IntNum,A,sum);
cout<<endl;
cout<<sum<<endl;
cout<<"是否繼續測試(輸入0則繼續不然中止)";
cin>>q;
system("cls");
}
}
5.運行結果
無溢出時:
溢出時:對代碼進行改動,在求和代碼函數中*4294967296(也就是2的32次方) 這樣在運行程序以後就會溢出,截圖以下:
6.實驗感想:此次實驗讓我明白了實驗代碼簡練的重要性,算法優化的重要性,這樣能夠節省運算時間,因此此次試驗我收穫不少,下次ios
實驗我會更加用心,學習到更多知識,讓我更上一層樓。算法
7.小組相片:數組