Here is the problem:
Given a list of integers, A0, A2, ... , An-1, each of which may be
positive or negative, find the sublist of integers Ai, ..., Aj which has
the maximum sum of any sublist. If all the integers are negative,
return 0.
A sublist has to start at some position in the original list, finish at some later position and
include every number which is in the original list between those positions. So, for
example if the list is {10,-20,11,-4,13,3,-5,-17,2,15,1,-7,8} then the answer
is 23 since this is the sum of the list {11,-4,13,3} and no other sublist has a higher
sum. The answer is always at least 0, because the empty list is always a possible sublist,
and its sum is 0.
What I have done is
import java.util.*; class Exercise6c { // Front end code for the problem set as Exercise 6 public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.println("Enter some numbers (all on one line, separated by commas):"); String line = input.nextLine(); String[] numbers = line.split(","); int[] array = new int[numbers.length]; for(int i=0; i<array.length; i++) array[i]=Integer.parseInt(numbers[i].trim()); int highSum = highestSum(array); System.out.println("The highest sum of a sublist of the numbers is: "+highSum); } public static int highestSum(int[] a) { int sum = 0; int sm = 0; for(int i = 0; i < a.length; i++){ for(int j = 1; j < a.length; j++){ // sum = a[i]; for (int k = 0; k < (j-i)+1 ; k++){ sum = sum + a[i+k]; if (sum > sm ){ sm = sum ; } } } } return sm ; // ... To be filled in ... } }
just look at method highestSum.( Apprently one of the applications is stock market analysis.)
Can anyone solve the problem of just altering the method highestSum, to find the solution to the task.