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);
}
}