Finding the longest non-negative sub array

前端 未结 3 880
粉色の甜心
粉色の甜心 2020-12-19 11:37

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

3条回答
  •  臣服心动
    2020-12-19 12:13

    HINTS

    You can do this in linear time by:

    1. First compute the cumulative sum of your array A
    2. Then compute an array B giving the greatest value in A to the right of index i
    3. And compute an array C giving the smallest value in A to the left of index i

    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:

    1. start with start=0
    2. increment end until B[end+1]<=C[start]
    3. increment start and return to step 2

    The greatest value of end-start corresponds to the longest subarray.

    Explanation

    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].

提交回复
热议问题