I\'m looking for an more efficient alternative to brute force for finding the longest sub array of an array with a non-negative sum. The numbers range from -5 to 5 in this a
You can do this in linear time by:
Both B and C will be non-increasing arrays.
Then for each start position in array C, compute the greatest end position in array B such that B[end]>C[start]. This can be done in linear time by:
The greatest value of end-start corresponds to the longest subarray.
The main idea is that once you have a cumulative sum of your array you can compute the value of a subarray by doing a subtraction.
For example, the array:
4 2 -5 3 0 -2
has cumulative values:
A = [4 6 1 4 4 2]
So to find the sum of the second, third, fourth entries (indices 1,2,3 with values 2,-5,3) we can compute:
A[3]-A[0] = 4 - 4 = 0
and so your problem now reduces to finding pairs of values in array A that are furthest apart and also have A[end]>A[start].