zoukankan      html  css  js  c++  java
  • 数组求和(二)

    题目:求一个二维数组中的最大子数组的和

    分析:以前做过一个一位数组的求和,现在改为二维数组,复杂了很多,但基本思想不变。经过几天的讨论,与程序的修改,实现了题目的要求。源代码如下:

    package com.su.test;
           public class Hellosu {
        public static void main(String[] args)
        {
             //测试用例
          int b[][]={{3,4,-7},{7,2,0},{-11,3,0}};
          int max=maxSubMatrix(b,b.length,b[0].length);
          System.out.println(max); 
        }
        public static  int maxSubArray(int ar[],int n)    //一维数组最大子数组
        {
            int max=ar[0];
            int k[]=new int[3];
            int b=ar[0];
            int i;
            for(i=1;i<n;i++)
            {
               if(b>0)
               {
                   b+=ar[i];  
               }
               else
               {
                   b=ar[i];
               }
                
               if(b>max)
               {
                   max=b;
               }
            }  
            return max;
        }
        public static  int maxSubMatrix(int p[][],int m,int n)    //二维数组最大子矩阵
        {
              int i,j,k,max=p[0][0],tempt;
             //记录每行的和
             int last_i=0,last_j=0;
             int sum[]=new int[m];
            for(i=0;i<n;i++)
           {
                for(k=0;k<m;k++)
                 sum[k]=0;
                     for(j=i;j<n;j++)
                    {
                        for(k=0;k<m;k++)
                       {
                         sum[k]+=p[k][j];
                       }
                        tempt=maxSubArray(sum,m);
                        if(tempt>max)
                        {
                         last_i=i;
                         last_j=j;
                         max=tempt;
                        }
                    }
                }
              System.out.println("从第"+(last_i+1)+"列开始,到第"+(last_j+1)+"结束");
          return max;
        }
     }
    总结:结对开发是我们练习的重点,主要是形成一个习惯:能设计算法,并且具有可读性;能找出别人写的代码中的错误,或者能简化程序代码。
  • 相关阅读:
    之三:CAAnimationGroup
    之二:CAKeyframeAnimation
    Core Animation
    swift基础语法(28- 继承与构造方法, 指定构造与便利构造方法)
    swift基础语法(26-继承,super关键字,override关键字,final关键字)
    swift基础语法(25- 下标subscripts)
    swift基础语法(24-方法,self关键字,mutating方法,类方法)
    swift基础语法(23- 属性,存储属性,延迟存储属性,计算属性,属性观察器,类属性)
    swift基础语法(22-类,类的恒等运算)
    swift基础语法(21-结构体,结构体构造器,定义成员方法)
  • 原文地址:https://www.cnblogs.com/wuwei123/p/3611862.html
Copyright © 2011-2022 走看看