0

I'm working on a problem on codeeval.com - http://codeeval.com/open_challenges/17/. "Write a program to determine the largest sum of contiguous integers in a list".

Input is a text file containing comma separated list of integers, one per line e.g.

-10, 2, 3, -2, 0, 5, -15

2,3,-2,-1,10

That input should produce 8 for the first line and 12 for the second. My answer is below, but I cannot see how to get 12 for the second line, so my question is mainly what am I missing, am I misinterpreting what's being asked for? (I get 13 for the answer)

N.B. - I live in Ireland so this is purely for my own experience, you won't be helping me with a job application! Also, I went through every similar question on here and couldn't find anything relevant.

If my interpretation of the question is incorrect, all I need is a point in the right direction, not necessarily code. (As in, can someone point out how the second line evaluates to 12 and not 13)

import java.util.*;
import java.io.*;

public class largest_sum {

    public static void main(String[] args) throws Exception { 

        FileReader input = new FileReader(args[0]);
        BufferedReader bufRead = new BufferedReader(input);
        String line;

        line = bufRead.readLine();

        while(line != null) { 
            addInts(line);
            line = bufRead.readLine();
        }
        bufRead.close();
        System.exit(0);
    }

    public static void addInts(String line) {
        String[] numbers = line.split(",");
        Integer largest = Integer.parseInt(numbers[0].trim());
        Integer secondLargest = 0;
        for(String s : numbers) {
            Integer converted = Integer.parseInt(s.trim());
            if(converted > largest) {

                secondLargest =  largest;
                largest = converted;
            }
        }
        System.out.println(largest + secondLargest);
    }
}
Saf
  • 517
  • 1
  • 9
  • 24
  • 5
    "I live in Ireland so this is purely for my own experience, you won't be helping me with a job application" - what does living in Ireland have to do with it? – Jon Skeet Sep 04 '12 at 10:12
  • Because it's a challenge for a job for people who can work in the US... I'm doing it just for experience. Not the job application. – Saf Sep 04 '12 at 10:16
  • 1
    Your mistake is that you are adding the two biggest numbers from the sequence. But they are not necessarily consecutive! In the considered case, the sequence `3, 10` is not a solution to the problem, however it's chosen by your algorithm. For the description of how the problem should be solved, see @mtsvetkov's answer. – Vlad Sep 04 '12 at 10:20
  • You code should declare that it throws `NumberFormatException` – Roman C Sep 04 '12 at 10:23
  • @JonSkeet - I could be politically incorrect and point out that it is the sort of thing that an Irishman would say :-) – Stephen C Sep 04 '12 at 10:30
  • "I live in Ireland so ... you won't be helping me with a job application!" No jobs in Ireland? :( – Peter Lawrey Sep 04 '12 at 10:30
  • Bwhahaha, no plenty of jobs for a programmer, just you need a Visa for US work. :P – Saf Sep 04 '12 at 10:34
  • @Saf There are jobs in London for which you don't need a vista. ;) – Peter Lawrey Sep 04 '12 at 10:37
  • @Peter, that's where I'm headed when I graduate, not too long to go :) – Saf Sep 04 '12 at 10:39

4 Answers4

5

I would suggest having a look at Kadane's algorithm.

Edit: As @Paolo and @Vlad pointed out - you're not getting the correct result because you are adding the largest two numbers, as opposed to looking for a sequence. Kadane's algorithm finds the largest sum of a sequence by first finding the largest sum ending at each position in your data set.

mtsvetkov
  • 885
  • 10
  • 21
  • A quick Google on that algorithm solved the problem instantly. Now I just need to make sure I understand it, very interesting, thank you. – Saf Sep 04 '12 at 11:19
2

The question is asking to find the greatest sum of contiguous integers. Your program is picking the largest and second largest and adding them together, not the same thing.

In the first line, the greatest sum is acheived by taking the subseqence:

2, 3, -2, 0, 5 

which sums to 8 (the fact that the 2 and -2 cancel out leaving you with effectively the largest + second largest numbers is a red herring).

In the second line the greatest sum is acheived by the taking the whole sequence:

2 + 3 + -2 + -1 + 10

which sums to 12.

Paolo
  • 22,188
  • 6
  • 42
  • 49
  • Thanks for clarifying, if I could let two questions be the answer I would! Gave it +1 anyways. – Saf Sep 04 '12 at 10:48
0

I have modified the your code with below algorithm. Basically If I have understood correctly it is like find valid integer on the right side then move to left side and find valid integer there then get the sum.

public static void main(String[] args) throws Exception {

    addInts("-10,2,3,-2,0,5,-15");
    addInts("2,3,-2,-1,10");
}

public static void addInts(String line) {
    String[] numbers = line.split(",");
    // First convert Strings to integer array

    int[] ints = new int[numbers.length];
    int count = 0;

    for (String number : numbers) {
        ints[count++] = Integer.parseInt(number);
    }

    // now find first valid and last valid

    int firstValidIndex = -1;
    int lastValidIndex = -1;
    for (count = 0;;) {
        if (ints[count] < 0 && firstValidIndex == -1) {
            count++;
            continue;
        } else {
            if (firstValidIndex == -1) {
                firstValidIndex = count;
                //Swap the loop here now we have to find backwards              
                count = ints.length - 1;
            } else {
                if (ints[count] < 0) {
                    count--;
                    continue;
                } else {
                    lastValidIndex = count;
                    break;
                }

            }

        }
    }

    // Calculate the sum now
    int sum = 0;
    for (count = firstValidIndex; count <= lastValidIndex; count++) {
        sum = sum + ints[count];
    }

    System.out.println(sum);
}

Output

8
12
Amit Deshpande
  • 19,001
  • 4
  • 46
  • 72
  • No, I think it's just a happy coincidence that those numbers worked out, I think they went out of their way to throw red herrings in the input & expected answer. The correct answer involves applying Kadane's algorithm - http://stackoverflow.com/questions/7233042/kadane-algorithm-in-java. Mind you, I didn't understand the question properly either, hence the posting here! – Saf Sep 04 '12 at 12:31
0
package com.salpe.scjp.algo;

public class Algo1 {

    private static int[] test = new int[] { -10, 2, 3, -2, 0, 5, -15 };

    public static void main(String[] args) {


        int highestSum = test[0];

        int higheststart = 0;
        int highestend = 0;

        for (int i = 0; i < test.length; i++) {

            for (int j = 0; j < test.length; j++) {
                if (i != j) {
                    System.out.print("[ " + i + ", " + j );
                    System.out.print(" = "+findSum(i, j) +"]");

                    if(highestSum <  findSum(i, j)){
                        highestSum =  findSum(i, j);
                        higheststart = i;
                        highestend = j;
                    }
                }

            }

            System.out.println("");

        }

        System.out.println("Highest Sum " +highestSum);
        toString(higheststart, highestend);

    }

    public static int  findSum(int i, int j) {

        int sum =0;

        for (int j2 = i; j2 <= j; j2++) {

            sum = sum +test[j2];

        }

        return sum;
    }


    public static int  toString(int i, int j) {

        int sum =0;

        for (int j2 = i; j2 <= j; j2++) {

            System.out.print(" ,"+test[j2]);

        }

        return sum;
    }

}


----------

[ 0, 1 = -8][ 0, 2 = -5][ 0, 3 = -7][ 0, 4 = -7][ 0, 5 = -2][ 0, 6 = -17]
[ 1, 0 = 0][ 1, 2 = 5][ 1, 3 = 3][ 1, 4 = 3][ 1, 5 = 8][ 1, 6 = -7]
[ 2, 0 = 0][ 2, 1 = 0][ 2, 3 = 1][ 2, 4 = 1][ 2, 5 = 6][ 2, 6 = -9]
[ 3, 0 = 0][ 3, 1 = 0][ 3, 2 = 0][ 3, 4 = -2][ 3, 5 = 3][ 3, 6 = -12]
[ 4, 0 = 0][ 4, 1 = 0][ 4, 2 = 0][ 4, 3 = 0][ 4, 5 = 5][ 4, 6 = -10]
[ 5, 0 = 0][ 5, 1 = 0][ 5, 2 = 0][ 5, 3 = 0][ 5, 4 = 0][ 5, 6 = -10]
[ 6, 0 = 0][ 6, 1 = 0][ 6, 2 = 0][ 6, 3 = 0][ 6, 4 = 0][ 6, 5 = 0]
Highest Sum 8
 ,2 ,3 ,-2 ,0 ,5
Neel Salpe
  • 1,287
  • 3
  • 15
  • 26