码迷,mamicode.com
首页 > 其他好文 > 详细

练习数值计算

时间:2015-04-24 15:47:05      阅读:126      评论:0      收藏:0      [点我收藏+]

标签:

找出一个整数数组中子数组之和的最大值,例如:数组[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);

    }

    

    

}

?

 

 

 

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

技术分享

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

练习数值计算

标签:

原文地址:http://www.cnblogs.com/FBean/p/4453463.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!