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


    要求:

    1、输入一个整数数组,数组里有整数也有负数;

    2、数组中连续的一个或多个整数组成一个子数组,每个子数组都有一个和;

    3、求所有子数组的和的最大值。要求时间负责度为O(n);

    设计思想:

    第一次以数组第一个元素向后加和直到最后一个元素,之后从第二个元素开始,例:有n个元素的数组A,则加和后存到n*(n+1)/2个元素的数组B中,之后对B数组元素进行排序,求得最大子数组的和;

    源代码:

    public static void main(String[] args) {
                Scanner sc = new Scanner(System.in);
                System.out.print("输入数组个数:");
                int n = sc.nextInt();
                System.out.print("输入数组:");
                int a[] = new int[n];
                for(int i=0; i<n; i++)
                    {
                    a[i] = sc.nextInt();
                    }
                sc.close();
                String intArrayString = Arrays.toString(a);
                System.out.println(large(a,n));  //打印最大子数组
    
        }
         private  static int max(int a,int b) {
             if(a>b) return a;
             else return b;
         }
        private  static int large(int a[],int n) {
            int max=a[0];
            int max2=0;       
            for (int i= 0; i< n; i++)
            {
            max2=max(max2+a[i],a[0]);   //几个连续最大的值
            max=max(max,max2);     //目前为止最大值
                 }
            return max;
        }
  • 相关阅读:
    eclipse工具
    Tag
    JSP模版
    Eclipse断点调试
    JavaBean
    验证码设计
    在IE中提示404错误
    序列化与反序列化
    文件编码问题
    强类型,弱类型和推断类型
  • 原文地址:https://www.cnblogs.com/KYin/p/10507836.html
Copyright © 2020-2023  润新知