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

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

要求:

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

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

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

思路:利用循环语句实现

代码:

#include<iostream>

#include<stdlib.h>

#include<iomanip>

using namespace std;

#define Max 100

void main ()

{   int n=5,m=5;  

int array[5][5];   

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

    {

     for(int j=0;j<m;j++)   

      {    

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

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

}   cout<<endl;  

}  

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

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

   { 

    for(int j=0;j<m;j++)   

   { 

    int k=i,l=j;    

   while(k<n)    

    {          

     while(l<m)        

     {              

       for(int a=i;a<k;a++)   

        {         

         for(int b=j;b<l;b++)        

           {       

             temp=temp+array[a][b];                  

          }    

       }                 

    if(temp>sum)                 

     {                   

      sum=temp;                  

    }     

     temp=0;     

     l++;          

  }    

      k++;     

    l=j ;    

  }            

}     

}   

cout<<sum;

}

截图:

总结:for循环和while语句的联合使用

原文地址:https://www.cnblogs.com/mingning/p/4537646.html