環形陣列問題
阿新 • • 發佈:2018-11-13
#include<iostream>
#define N 1000
using namespace std;
int Compare(int Group[], int Length)
{
int MaxSum[N][2];
MaxSum[0][0] = MaxSum[0][1] = Group[0];
for (int i = 1; i < Length; i++)
{
MaxSum[i][0] = __max(MaxSum[i - 1][0], MaxSum[i - 1][1]);
MaxSum[i][1] = __max(MaxSum[i - 1][1] + Group[i], Group[i]);
}
return __max(MaxSum[Length - 1][0], MaxSum[Length - 1][1]);
}
int main()
{
int Number[N];
int Length;
int y,x,a;
a=0;
cout<<"請輸入陣列的長度:"<<endl;
cin>>x;
cout<<"請輸入一個環形陣列:"<<endl;
cin>>Number[0];
Length=1;
while (getchar()!='\n')
{
cin>>Number[Length++];
}
for(int z=1;z<x+1;z++)
{
Number[Length++]=Number[z-1];
Number[z-1]=0;
/*for(y=0;y<Length;y++)
cout<<Number[y]<<endl;//測試能否正確的生成切斷後的環形陣列*/
/*printf("%d",Compare(Number, Length));//返回每個切斷後陣列的值*/
if(a<Compare(Number, Length))
a=Compare(Number, Length);
}
cout << "該陣列中的最大的子陣列和為:";
cout << a << endl;
system("pause");
return 0;
}
#define N 1000
using namespace std;
int Compare(int Group[], int Length)
{
int MaxSum[N][2];
MaxSum[0][0] = MaxSum[0][1] = Group[0];
for (int i = 1; i < Length; i++)
{
MaxSum[i][0] = __max(MaxSum[i - 1][0], MaxSum[i - 1][1]);
MaxSum[i][1] = __max(MaxSum[i - 1][1] + Group[i], Group[i]);
}
return __max(MaxSum[Length - 1][0], MaxSum[Length - 1][1]);
}
int main()
{
int Number[N];
int Length;
int y,x,a;
a=0;
cout<<"請輸入陣列的長度:"<<endl;
cin>>x;
cout<<"請輸入一個環形陣列:"<<endl;
cin>>Number[0];
Length=1;
while (getchar()!='\n')
{
cin>>Number[Length++];
}
for(int z=1;z<x+1;z++)
{
Number[Length++]=Number[z-1];
Number[z-1]=0;
/*for(y=0;y<Length;y++)
cout<<Number[y]<<endl;//測試能否正確的生成切斷後的環形陣列*/
/*printf("%d",Compare(Number, Length));//返回每個切斷後陣列的值*/
if(a<Compare(Number, Length))
a=Compare(Number, Length);
}
cout << "該陣列中的最大的子陣列和為:";
cout << a << endl;
system("pause");
return 0;
}