結對練習二

來源:互聯網
上載者:User

標籤:返回   多個   .com   alt   ace   代碼   技術分享   return   using   

一、題目要求

題目:返回一個二維整數數組中最大子數組的和。要求:輸入一個二維整形數組,數組裡有正數也有負數。二維數組首尾相接,象個一條首尾相接帶子一樣。數組中連續的一個或多個整數組成一個子數組,每個子數組都有一個和。求所有子數組的和的最大值。要求時間複雜度為O(n)。 代碼:

 

#include <iostream>
using namespace std;

int maxSubArray(int **a,int n,int m)
{
int **p=new int*[n];
int i,j;
if(m==0||n==0)
return 0;
//計算p[i][j]
for(i=0;i<n;i++)
{
p[i]=new int[m];
for(j=0;j<m;j++)
{
if(i==0)
{
if(j==0)
p[i][j]=a[i][j];
else
p[i][j]=p[i][j-1]+a[i][j];
}
else
{
if(j==0)
p[i][j]=p[i-1][j]+a[i][j];
else
p[i][j]=p[i][j-1]+p[i-1][j]-p[i-1][j-1]+a[i][j];
}
}
}
//計算二維數組最大子數組的和
int temp;
int max=a[0][0];
int ans;
//如果m==1
if(m==1)
{
for(i=0;i<n;i++)
{
for(j=i;j<n;j++)
{
if(i==0)
{
temp=p[j][m-1];
}
else
{
temp=p[j][m-1]-p[i-1][m-1];
}
if(ans<temp)
ans=temp;
}
}
}
else
{
for(i=0;i<n;i++)
{
for(j=i;j<n;j++)
{
if(i==0)
{
temp=p[j][m-1]-p[j][m-2];
}
else
{
temp=p[j][m-1]-p[j][m-2]-p[i-1][m-1]+p[i-1][m-2];
}
for(int k=m-2;k>=0;k--)
{
if(temp<0)
temp=0;
if(i==0)
{
if(k==0)
temp+=p[j][k];
else
temp+=p[j][k]-p[j][k-1];
}
else
{
if(k==0)
temp+=p[j][k]-p[i-1][k];
else
temp+=p[j][k]-p[j][k-1]-p[i-1][k]+p[i-1][k-1];
}
if(ans<temp)
ans=temp;
}
}
}
}
return ans;
}

int main()
{
int n,m,temp;
int a1,a2;
int k=0;
printf("請輸入二維數組的行數和列數:\n");
scanf("%d %d",&n,&m);
int i,j;
int **a=new int*[n];
printf("請輸入%d*%d個二維數組元素:\n",n,m);
for(i=0;i<n;i++)
{
a[i]=new int[m];

for(j=0;j<m;j++)
{
scanf("%d",&a[i][j]);
}
}
int ans=maxSubArray(a,n,m);
printf("二維數組的最大子數組之和是:%d\n",ans);
for(a2=0;a2<m-1;a2++)
{ for(i=0;i<n;i++)
{ temp=a[i][0];
for(j=1;j<m;j++)
{a[i][j-1]=a[i][j];}
a[i][m-1]=temp;
}

for(i=0;i<n;i++)
{
for(j=0;j<m;j++)
{

if(k%m==0)
{cout<<endl;}
cout<<a[i][j]<<" ";
k++;
}

}

a1=maxSubArray(a,n,m);
printf("二維數組的最大子數組之和是:%d\n",a1);
}
return 0;
}

 

運行結果:

結對人照片:

 

結對練習二

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.