Here is an idea:
- Sort the 2nd to Nth elements descending (the problem stays the same).
- Build the cumulative sum in reverse. [1 4 3 2] => [10 9 5 2] to get an upper bound for the highest number you can still reach with the remaining integers.
- Use the bounds from the reverse cumulative sum to prune.
In Java:
// assuming the numbers are positive
// (ignore operator when parsing, line.split("[ +-]+") will do)
public static int canReach0(int[] numbers) {
sort(numbers, 1); // sort(array, offset) doesn't matter what algorithm
// for 300 elements and compared to the complexity of the rest
int[] revSum = new int[numbers.length];
revSum[numbers.length - 1] = numbers[numbers.length - 1];
for (int i = numbers.length - 2; i >= 0; i--)
revSum[i] = revSum[i + 1] + numbers[i];
int sum = numbers[0];
if (sum == revSum[1])
return 0;
return solve(numbers, 1, sum, revSum);
}
private static int solve(int[] numbers, int index, int sum, int[] revSum) {
if (index == numbers.length - 1)
return -1;
int high = sum + numbers[index];
if (high == revSum[index + 1] ||
(high < revSum[index + 1] && solve(numbers, index + 1, high, revSum) == 0))
return 0;
int low = sum - numbers[index];
if (low == -revSum[index + 1] ||
(low > -revSum[index + 1] && solve(numbers, index + 1, low, revSum) == 0))
return 0;
return -1;
}