Это код, который у меня есть:
Код: Выделить всё
import java.util.ArrayList;
public class Problem1 {
public static void main(String[] args) {
int array1[] = { 3, -4, 2, -3, -1, 7, -5 };
int size1 = array1.length;
int array2[] = { 1, 2, -1, 3, -6, -1, 4, 5 };
int size2 = array2.length;
int array3[] = { 10, -8, 3, -7, 2, -3 };
int size3 = array3.length;
System.out.println(smallestSum(array1, size1));
System.out.println(smallestSum(array2, size2));
System.out.println(smallestSum(array3, size3));
}
static String smallestSum(int array[], int size) {
int smallEnding = Integer.MAX_VALUE;
int smallCurrent = Integer.MAX_VALUE;
ArrayList subArray = new ArrayList();
for (int i = 0; i < size; i++) {
if (smallEnding > 0) {
smallEnding = array[i];
} else {
smallEnding += array[i];
subArray.add(array[i - 1]);
}
smallCurrent = Math.min(smallCurrent, smallEnding);
}
return ("The smallest sum contiguous subarray of the array is " +
subArray.toString() + " with a sum of "
+ Integer.toString(smallCurrent));
}
}
Код: Выделить всё
The smallest sum contiguous subarray of the array is [-4, 2, -3, -1] with a sum of -6
The smallest sum contiguous subarray of the array is [-1, -6, -1, 4] with a sum of -7
The smallest sum contiguous subarray of the array is [-8, 3, -7, 2] with a sum of -13
Подробнее здесь: https://stackoverflow.com/questions/790 ... ot-the-sum