【问题标题】:Finding largest sum of consecutive numbers in an array查找数组中连续数字的最大总和
【发布时间】:2019-03-15 02:30:42
【问题描述】:

对于我正在制作的这个程序,我有几个问题要找出列表中连续数字的最大总和。请注意,这与在数组中找到最大的连续整数之和不同。基本上,给定一个 ex 列表。 2, -1, 3,4,9 .... 等高达 100 万,我需要找到最大的连续数字总和(在上面给出的列表中,3,4 是连续的,因此总和将为 7)。所以我能理解的是我需要一个循环来遍历列表并检查数字是否连续。我的循环基于这样一个事实,即减去连续数字后将等于 -1,但我的 if 语句似乎总是出现 ArrayINdexOutOfBounds 错误。举个例子,假设列表是

1 2 3 4
3 -1 4 5

这是我的代码;

public class ProgramCRedo {

//This method reads each line and checks for the largest sum of consecutive numbers in a list
//This method does not have a return value, information is outputted once it exists
//This method has one parameter, it is string list taken from the input file
public static void checkLine (String line){
    String[] numbers = line.split(" ");
    int sum = 0;
    int largestSum = 0; 
    int [] savedNums = new int [numbers.length];

    for(int i = 0; i<savedNums.length; i++) { //loops through the list
        savedNums [i] = Integer.parseInt(numbers[i]);
        if((savedNums[i] - (savedNums[i+1])) == -1) { //checks if numbers are consecutive
            sum += (savedNums[i] + (savedNums[i+1])); //if true, adds them up to a sum
        }
        System.out.println(sum);
//          System.out.println(savedNums[i]);
        }
    }
}
public static void main(String[] args) {

    try{
        BufferedReader bf = new BufferedReader (new FileReader("input.txt"));
        String line;

        line = bf.readLine(); //reads line
        //String line1= null; //skips first line    

        while(line != null){    //keeps looping until no more lines     
            checkLine(line); // uses list to check each line in file
            line = bf.readLine();
        }
        bf.close();

    }catch(FileNotFoundException e){ // catches exceptions
        System.out.println("FILE NOT FOUND!");
    }catch(IOException e){
        System.out.println("Reading Error!");
    }catch(NumberFormatException e) {
        System.out.println("Invalid Input Entered");
    }

    System.out.println("Program is complete");
}

这是我的一些问题

  1. 为什么我的方法中的 if 语句给我一个 ArrayIndexOutOfBounds 异常?
  2. 作业规定每个测试用例的整数列表将在单行文本中给出,列表中的每个整数用一个空格分隔。您可以假设每个案例的最大列表大小为 1,000,000 - 我在哪里以及如何输入此检查以获取最多 100 万个整数的列表?

谢谢,这是用 JAVA 写的。

更新:我发现数组越界问题。现在发生的情况是,当我打印出此处给出的列表示例的总和时,我得到 0 和 -1。这是不正确的。我将尝试追踪这一点,但如果有人有任何想法,请告诉我。

【问题讨论】:

  • i 处于最大值时,savedNums[i+1] 将超过数组的长度
  • 读行时使用"line = bf.readLine().substring(0,1000000);"这会将您的字符长度限制为 100 万,并且在创建 saveNums 数组时,您已经创建了与输入行中的数字长度相等的数组,但您没有在数组中添加这些数字。

标签: java arrays string loops integer


【解决方案1】:

作业说明每个测试用例的整数列表将在单行文本中给出,列表中的每个整数用一个空格分隔。您可以假设每个案例的最大列表大小为 1,000,000 - 我在哪里以及如何输入此检查以获取最多 100 万个整数的列表?

上面的语句告诉你假设将有 100 万个整数,以防你需要初始化一个整数数组。但是,由于您使用的是String[] numbers = line.split(" ");,因此您无需担心这一点。但是如果你的教授真的想排除那些超过 100 万个整数的行,那么一种方法是在 String[] numbers = line.split(" "); 之后进行检查(查看下面的代码了解详细信息)

现在发生的情况是,当我打印出此处给出的列表示例的总和时,我得到 0 和 -1。这是不正确的。我将尝试追踪这一点,但如果有人有任何想法,请告诉我。

上面的语句发生是因为你的代码对于这一行永远不会是真的:

if((savedNums[i] - (savedNums[i+1])) == -1) {

条件永远不会计算为true,因为您只是通过执行int [] savedNums = new int [numbers.length]; 来初始化savedNums,这意味着如果numbers.length 为3,那么您的savedNums 将是[0, 0, 0],因为默认值为一个 int 数组是 0。

您只是在通过执行savedNums [i] = Integer.parseInt(numbers[i]); 迭代循环时设置savedNums 的每个元素的值,因此savedNums[i+1] 将始终为0。

同样做sum += (savedNums[i] + (savedNums[i+1]));是不正确的,因为有些元素会在sum中添加两次。
例如,如果您有 savedNums = [1, 2, 3] ,那么每个 ite 中总和的值将是:
第一次迭代:

i = 0;
sum = 0; // initial
sum = sum + savedNums[i] + savedNums[i+1];
sum = 0 + 1 + 2;
sum = 3;

第二次迭代:

i = 1;
sum = 3; // value after first iteration
sum = sum + savedNums[i] + savedNums[i+1];
sum = 3 + 2 + 3; // 2 was added twice
sum = 8;

因此,您的 sum 将是 8 而不是 6。

我已经修改了您的代码,使其可以按预期工作,只需阅读代码 cmets 了解详情。

public static void checkLine(String line) {
    String[] numbers = line.split(" ");
        if (number.length > 1000000) { //if line contains more than 1 million integers
                 return;
        }
    int sum = 0;
    int largestSum = 0;

    for (int i = 0; i < numbers.length - 1; i++) { // loops through the list
        int currentNum = Integer.parseInt(numbers[i]);
        int nextNum = Integer.parseInt(numbers[i + 1]);
        if (nextNum - currentNum == 1) { // checks if numbers are consecutive
            // check if sum is 0, which means that this is the first time a consecutive
            // number is found
            // example [1,2,3,4]
            if (sum == 0) { // this will be true when currenNum is 1 and nextNum is 2
                sum = currentNum + nextNum; // since it is the first time a consecutive number is found add both
                                            // numbers
            } else { // this will be executed when currenNum is 2 and nextNum is 3
                sum += nextNum; // since it is not the first time a consecutive number is found only add the
                                // next number, no need to add the current number since it is already added in
                                // the above condition
            }
        } else {
            sum = 0;
        }
        if (largestSum < sum) {
            largestSum = sum;
        }
    }

    System.out.println(sum);
}

示例输入:

1 2 3 4
3 -1 4 5
1 2 4 5

输出:

10
9
9

【讨论】:

    猜你喜欢
    • 2015-07-27
    • 2013-09-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多