二維數組求和

來源:互聯網
上載者:User

標籤:

                                                                                               二維數組求和

輸入一個二維的整形數組,數組裡有正數也有負數,數組中連續的一個或多個整數組成一個二維子數組,每個子數組都有一個和。求所有子數組的和的最大值。

解題思路:由於原來做的這個時間有一點久遠,我記得當時的思路就是將二維數組轉化為一維數組,然後利用原來的一維數組求和的方式進行計算。

原始碼

package shengcheng;import java.util.Scanner;import org.junit.Test;public class Erwei{    @Test    public void fun()    {       int [][]a=new int[4][4];       Scanner write=new Scanner(System.in);       for(int i=0;i<4;i++)       {           for(int j=0;j<4;j++)           {               a[i][j]=write.nextInt();           }       }       int  max=-200000;       int []sum=new int [4];            int  add =-200000 ;       for(int i=0;i<4;i++)       {           for(int l=0;l<4;l++)           {               sum[l]=0;           }           for(int j=i;j<4;j++)           {               for(int k=0;k<4;k++)               {                   sum[k]+=a[j][k];               }                       add=DP(sum,4);           }           if(add>max)           {               max=add;           }       }              System.out.println(max);    }           public  int DP(int  a[],int n)   {       int i;       int  []temp=new int [100];       int  max=a[0];       for(i=1,temp[0]=a[0];i<n;i++)       {            if(temp[i-1]>0)                temp[i]=temp[i-1]+a[i];            else                 temp[i]=a[i];            if(temp[i]>max)                max=temp[i];       }       return max;  }}

運行:

 

二維數組求和

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.