最大和子数组和

设计思路

思路

先求数组长度为一的子数组的和,再求数组长度为二的子数组的和,依次下去求得所有子数组的和,然后比较.

代码及截图

package 数组;

import java.util.Random;

import java.util.Scanner;

public class shuzu4 {

       public static void main(String[] args) {

              // TODO Auto-generated method stub

              int a[],b[];

              int i,ii,j=0,g,h,m=0,n=0,hh;

              Scanner scanner = new Scanner(System.in);

              System.out.print("输出随机产生的数组的长度:");

              g=scanner.nextInt();

              a=new int[g];

              for(i=0;i<g;i++)

              {

                     Random random = new Random();

                     a[i]=random.nextInt(19);

                     a[i]=a[i]-9;

                     System.out.print(a[i]);

                     System.out.print(" ");

              }

                     System.out.println("");

              scanner.close();

              b=new int[(g+1)*g/2];

             

              System.out.print("子数组的和依次为:");

              for(h=1;h<=g;h++)

              {

                     hh=h;

                     for(ii=0;ii<g-h+1;ii++)

                         {for(i=n;i<hh;i++)

                                m=m+a[i];

                         System.out.print(m);

                            System.out.print(" ");

                         b[j]=m;j+=1;

                         m=0;n+=1;hh+=1;}

                     n=0;

              }

              System.out.println("");

              for(j=0;j<(g+1)*g/2;j++)

              {

                     if(b[j]>m)m=b[j];

              }

              System.out.print("最大的和为:");

                     System.out.print(m);

       }

}

 

原文地址:https://www.cnblogs.com/feifeishi/p/4358007.html