I need to write a Java program to determine the largest sum of contiguous intege
ID: 2246896 • Letter: I
Question
I need to write a Java program to determine the largest sum of contiguous integers in a sequence. So if the input is -10, 2, 3, -2, 0, 5, -15 the largest sum is 8. If the input is 2,3,-2,-1,10 the largest sum is 12.
I wrote something, but it's not given me the largest sum. Can you fix my code?
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
FileReader input = new FileReader(args[0]);
BufferedReader in = new BufferedReader(input);
String line;
line = in.readLine();
while(line != null){
summNum(line);
line = in.readLine();
}
in.close();
System.exit(0);
}
public static void summNum(String line){
String[] num = line.split(",");
Integer largest = Integer.parseInt(num[0].trim());
Integer scndLargest = 0;
for(String s : num){
Integer converted = Integer.parseInt(s.trim());
if(converted > largest){
scndLargest = largest;
largest = converted;
}
}
System.out.println(largest+scndLargest);
}
}
Explanation / Answer
**Here I found that you are just find the sum of the largest and second elements of an array. So in order to determine the largest sum of contiguous integers in a sequence you need compare sum of elements by adding a element when it increases the sum.
So My suggestion is store the integers in array an pass them a function called maxContiguousSubArray which takes an array as a parameter return an integer which is largest sum of contiguous integers in a sequence.
So the final program will be like:
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
FileReader input = new FileReader(args[0]);
BufferedReader in = new BufferedReader(input);
String line;
line = in.readLine();
while(line != null){
summNum(line);
line = in.readLine();
}
in.close();
System.exit(0);
}
static int maxContiguousSubArray(int myarray[])
{
int array_length = myarray.length;
int max_sum_till = Integer.MIN_VALUE;
int max_sum_ending = 0;
for (int itr = 0; itr < array_length; itr++)
{
max_sum_ending = max_sum_ending + myarray[itr];
if (max_sum_till < max_sum_ending){
max_sum_till = max_sum_ending;
}
if (max_sum_ending < 0){
max_sum_ending = 0;
}
}
return max_sum_till;
}
public static void summNum(String line){
String[] num = line.split(",");
int myarray[]=new int[num.length];
int count = 0;
for(String s : num){
Integer converted = Integer.parseInt(s.trim());
myarray[count] = converted;
count++;
}
int maxSum = maxContiguousSubArray(myarray);
System.out.println(maxSum);
}
}