Subsequence sum

后端 未结 5 1195
天命终不由人
天命终不由人 2021-01-30 18:23

Given an array of integers eg [1, 2, -3, 1] find whether there is a sub-sequence that sums to 0 and return it (eg [1, 2, -3] or [2,

5条回答
  •  梦谈多话
    2021-01-30 19:05

    Make a new array with each element equal to the sum of the previous elements plus that one.

    Input:

    1  4 -3 -4  6  -7  8 -5
    

    Becomes:

    1  5  2  -2  4  -3  5  0
       ^                ^
    

    Then look for elements that match in the resulting array.

    Since these represent locations where the overall change in the function is zero, you will find that if their position is i and k then the subsequence (i+1, k) is a zero-sum subsequence. (In this case, [2:6]).

    Additionally, any zeros in the table indicate that the subsequence (0, k) is a zero-sum subsequence. For the lookup, a hash table or other fast collision locator makes this O(N) to perform.

提交回复
热议问题