• 数组


    整形数组最大子数组的和

     

    要求求出整型数组的最大子数组的和,要求复杂度o(n)

    首先想到直接依次遍历,复杂度n三次方

    package shuzu;
    import java.util.Scanner;
    public class Shuzu {
     public static void main(String[] args) {
       Scanner sc = new Scanner(System.in);
             int[] a = new int[5];
             // 控制台输入数组值
             for (int i = 0; i < a.length; i++) {
                 System.out.println("请输入第" + (i + 1) + "个数字:");
                 int num = sc.nextInt();
                 a[i] = num;
             }
             int max=a[0];
             sc.close();
             for(int j=0;j<a.length;j++) {
              for(int k=0;k<a.length;k++) {
               int sum= 0;
               for(int l=0;l<a.length;l++) {
                sum+=a[l];
               }
               if(sum>max) max=sum;
              }
             }
             System.out.println(max);
             return;
     }
    }
     
     
    后来想到一个新的方法
    package shuzu;
    import java.util.Scanner;
    public class shuzu2 {
     public static void main(String[] args) {
      // TODO Auto-generated method stub
        Scanner sc = new Scanner(System.in);
              int[] a = new int[20];
              // 控制台输入数组值
              for (int i = 0; i < a.length; i++) {
                  System.out.println("请输入第" + (i + 1) + "个数字:");
                  int num = sc.nextInt();
                  a[i] = num;
              }
              sc.close();
              
              int max=a[0];
              int sum=a[0];
              for(int i=1;i<a.length;i++) {
               if(sum<0)
                sum=a[i];
               else 
                sum+=a[i];
               if(sum>max) max=sum;
              }
              System.out.println(max);
     }
    }
  • 相关阅读:
    Currency Exchange
    Robot Motion
    Crashing Robots
    Parencodings
    Y2K Accounting Bug
    Tautology
    Power of Cryptography
    Radar Installation -poj 1328
    The Pilots Brothers' refrigerator
    【java】之cron表达式
  • 原文地址:https://www.cnblogs.com/jiaoaoshirenjinbu/p/13036369.html
Copyright © 2020-2023  润新知