I am looking for a more effective alternative to brute force for finding the longest auxiliary array array with non-negative sum. Numbers range from -5 to 5 in this array.
For example, if you have an array A:
4 2 -5 3 0 -2 -2 -3 -4 -4 -3 -2 1
then the longest non-negative auxiliary array
4 2 -5 3 0 -2 -2 -3 4, with a length of 9
The solution I think of is to stick with the best solution and the best suffix, where the best suffix always ends with the last point checked A[i]. If the best suffix is longer than the best solution, we update the best solution for the best suffix.
The suffix will be made from a negative subarray sandwiched between two positive auxiliary arrays. So, in this case, starting from left to right:
4 2 - the first positive auxiliary matrix -5 - negative auxiliary array 3 0 -2 - the second positive auxiliary array
The program then checks to see if the sum of the two positive auxiliary arrays is greater than the negative auxiliary array. If so, then the best suffix will be the new first positive submatrix. If not, the first positive and negative auxiliary array are discarded, and the second positive auxiliary array becomes the first auxiliary array, etc.
Theoretically, the program should be able to incrementally check the best solution in linear time.
But this answer seems wrong.
, , ,
!