主要思想是使用两个索引迭代数组:正元素和负元素。当总和为负时,我们将搜索下一个正元素(使用相应的迭代器)以添加到总和中,否则 - 为负元素。
此代码应该可以工作:
public final class ArrayAdder {
@NotNull
private final int[] array;
private int sum;
public ArrayAdder(@NotNull int[] array) {
this.array = array;
}
public int sum() {
sum = 0;
final IntPredicate positive = v -> v > 0;
final Index positiveIndex = new Index(positive);
final Index negativeIndex = new Index(positive.negate());
while (positiveIndex.index < array.length || negativeIndex.index < array.length) {
sum += sum < 0 ? sum(positiveIndex, negativeIndex) : sum(negativeIndex, positiveIndex);
}
return sum;
}
private int sum(@NotNull Index mainIndex, @NotNull Index secondaryIndex) {
int localSum = 0;
// searching for the next suitable element
while (mainIndex.index < array.length && secondaryIndex.sign.test(array[mainIndex.index])) {
mainIndex.index++;
}
if (mainIndex.index < array.length) {
localSum += array[mainIndex.index++];
} else {
// add the remaining elements
for (; secondaryIndex.index < array.length; secondaryIndex.index++) {
if (secondaryIndex.sign.test(array[secondaryIndex.index])) {
localSum += array[secondaryIndex.index];
}
}
}
return localSum;
}
private static final class Index {
@NotNull
private final IntPredicate sign;
private int index;
public Index(@NotNull IntPredicate sign) {
this.sign = sign;
}
}
}