zoukankan      html  css  js  c++  java
  • 练习数值计算

    找出一个整数数组中子数组之和的最大值,例如:数组[1,-2,3,5,1],返回 8 (因为符合要求的子数组是[3,5]);数组[1,-2,3,-8,5,1],返回 6 (因为符合要求的子数组是[5,1]);数组[1,-2,3,-2,5,1],返回 7 (因为符合要求的子数组是[3,-2,5,1])。

    import java.util.Scanner;

    import java.io.*;

    public class Maxarr{

            public static void main(String[] args){

                  int[]a = null;

                  Scanner input = new Scanner(System.in);

                  int len=0;

                  System.out.print("请输入数组的长度:");

                  try{

                         len = Integer.parseInt(input.nextLine());

                  }catch(Exception e){

                  }

                  a = new int[len];

                  System.out.println("a.length ="+a.length);

                 for(int i=0;i

                 System.out.print("请输入数值:");

                 a[i] = input.nextInt();

               }

               System.out.println();

              System.out.print("该数组为:");

              for(int i=0;i

       

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

             }

             int sum = 0,max = 0;

            for(int i=0;i

            sum = 0;

            for(int j=i;j

            sum += a[j];

            if(sum>max)

             max = sum;

            }

    }

            System.out.println();

           System.out.println("该数组之和的最大值为 "+max);

        }

        

        

    }

    该程序 首先指定一个数组的长度,然后进行赋值,​再根据下面的算法 找出子数组之和的最大值

    虽然 这个方法有些蛮力, 但是也是对初步了解算法的一种很好的解决方案。

    夜落乌啼霜满天,江枫渔火对愁眠。
  • 相关阅读:
    消息队列简介
    docker快速构建oracle数据库
    MySQL读写分离之amoeba
    Python替换文件内容
    Nginx图片及样式文件不记录访问日志
    shell方式切割tomcat日志
    split命令
    orange安装文档
    openresty安装文档
    MySQL中kill所有慢查询进程和锁表进程
  • 原文地址:https://www.cnblogs.com/FBean/p/4453463.html
Copyright © 2011-2022 走看看